2020-04-13 10:08:59 +00:00
|
|
|
from django.db.models import Model, CharField, BooleanField
|
|
|
|
|
|
|
|
from core.classes.sms import BaseSMSProvider, SMSNotSent
|
|
|
|
|
|
|
|
from urllib.parse import quote_plus
|
|
|
|
from urllib.request import urlopen
|
|
|
|
from typing import Union
|
|
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
|
|
|
# Create your models here.
|
|
|
|
|
|
|
|
class PlaySMSServer(Model, BaseSMSProvider):
|
|
|
|
name = CharField(max_length=255)
|
|
|
|
logo = CharField(max_length=255)
|
|
|
|
https = BooleanField(default=True)
|
|
|
|
host = CharField(max_length=255)
|
|
|
|
username = CharField(max_length=255)
|
|
|
|
token = CharField(max_length=255)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def is_active(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def getError(status):
|
2020-04-13 18:03:01 +00:00
|
|
|
if status["error_string"]:
|
|
|
|
return status["error_string"]
|
2020-04-13 10:08:59 +00:00
|
|
|
try:
|
2020-04-13 18:03:01 +00:00
|
|
|
if int(status["data"][0]["error"]):
|
|
|
|
return int(status["data"][0]["error"])
|
2020-04-13 10:08:59 +00:00
|
|
|
finally:
|
|
|
|
return
|
|
|
|
|
|
|
|
def sendSMS(self, recipients: Union[str, list], message: str):
|
|
|
|
'''Send an SMS message to one or more recipients
|
|
|
|
|
|
|
|
:param recipients: Recipient phone number as a string, or a list of multiple phone number strings
|
|
|
|
:param message: Message to be sent as a string
|
|
|
|
'''
|
|
|
|
|
|
|
|
if isinstance(recipients, list):
|
|
|
|
recipients = ",".join(recipients)
|
|
|
|
|
2020-04-13 18:03:01 +00:00
|
|
|
url = 'http%s://%s/index.php?app=ws&u=%s&h=%s&op=pv&to=%s&msg=%s' % ("s" if self.https else "", self.host, self.username, self.token, recipients, quote_plus(message))
|
2020-04-13 10:08:59 +00:00
|
|
|
|
2020-04-13 18:03:01 +00:00
|
|
|
print(url)
|
2020-04-13 10:08:59 +00:00
|
|
|
response = urlopen(url)
|
|
|
|
|
|
|
|
status = json.loads(response.read().decode())
|
2020-04-13 18:03:01 +00:00
|
|
|
print(status)
|
2020-04-13 10:08:59 +00:00
|
|
|
|
|
|
|
error = PlaySMSServer.getError(status)
|
|
|
|
|
|
|
|
if error:
|
|
|
|
raise SMSNotSent(f'An error occurred trying to send the SMS: {error}')
|