You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
192 lines
7.9 KiB
192 lines
7.9 KiB
import time
|
|
from config.settings import base as settings
|
|
from celery import shared_task
|
|
import requests
|
|
import json
|
|
import logging
|
|
# import firebase_admin
|
|
# from firebase_admin import credentials, messaging
|
|
# import firebase_admin
|
|
# from firebase_admin import credentials, messaging
|
|
from google.oauth2 import service_account
|
|
import google.auth.transport.requests
|
|
|
|
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(levelname)s - %(message)s'
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# تنظیمات Firebase
|
|
data = {
|
|
"type": "service_account",
|
|
"project_id": "imamjavad-25c31",
|
|
"private_key_id": "1edc90fb80a335809c4b04a713403355ff4e8bd0",
|
|
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCM57lia6vNNzJL\nYBwFcx49sFPXtrYKkrRhtDN13EOnF2j+y8vlwtqYR6P7HB1l10GyHx3mlN8XpYXN\n24yrTsK6WugqPdWGl/z/BgqHximH+v4NCPQTBr3lemHbTXlEkhNtmaf9zM8IzsXP\nEzD4z5u9hy3AgfZdHKO0isTvxRTuTlpTKU3PQDwiIjfb6Bk8IjfjrDQqWbHLC4am\nidwM5F+L8ecAyhVe/G7IXAflqyi4zVM/hM5FiAknA5FmyfGd9HCxaLkw3Dqtnof8\nqflJmZp0vptT3Lte7ObeUEMoRoT0bZt6DbMBI+w19OIBu0ne0OjLu/1z4CFYoR+r\nAeWGvWCHAgMBAAECgf9HnQx/FY90oO5gtiLdE/pnJxqSMtjEhufRazaDd4vOYKXD\nhLQ5EkFcsij66PnPHiZiC+BfbUpnSIAqrmsliXBSYv4OCELTJU/FovcMfHG7qtU7\nIBjsrw64ISXT+ow1+EEEAWm1eA0WwjmOBTL7CTPJA3l2QXrYu5ki8IDuP1i5UwKu\nSR3kW0+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|
|
"client_email": "firebase-adminsdk-fbsvc@imamjavad-25c31.iam.gserviceaccount.com",
|
|
"client_id": "103207313184637638669",
|
|
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
|
"token_uri": "https://oauth2.googleapis.com/token",
|
|
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
|
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40imamjavad-25c31.iam.gserviceaccount.com",
|
|
"universe_domain": "googleapis.com"
|
|
}
|
|
|
|
PROJECT_ID = 'imamjavad-25c31'
|
|
BASE_URL = 'https://fcm.googleapis.com'
|
|
SCOPES = ['https://www.googleapis.com/auth/firebase.messaging']
|
|
FCM_ENDPOINT = f'v1/projects/{PROJECT_ID}/messages:send'
|
|
FCM_URL = f'{BASE_URL}/{FCM_ENDPOINT}'
|
|
|
|
def _get_access_token():
|
|
"""Retrieve a valid access token that can be used to authorize requests.
|
|
|
|
:return: Access token.
|
|
"""
|
|
credentials = service_account.Credentials.from_service_account_info(
|
|
data, scopes=SCOPES)
|
|
request = google.auth.transport.requests.Request()
|
|
credentials.refresh(request)
|
|
return credentials.token
|
|
|
|
|
|
# @shared_task
|
|
async def send_notification(ids: list, title: str = None, body: str = None, data=None,
|
|
extra_notification_kwargs: dict = None) -> list:
|
|
if not ids:
|
|
return []
|
|
|
|
chunked_ids = [ids[i:i + 500] for i in range(0, len(ids), 500)]
|
|
|
|
responses = []
|
|
for chunk in chunked_ids:
|
|
|
|
|
|
access_token = _get_access_token()
|
|
headers = {
|
|
'Authorization': f'Bearer {access_token}',
|
|
'Content-Type': 'application/json',
|
|
}
|
|
payload = {
|
|
'message': {
|
|
'token': chunk[0],
|
|
'notification': {
|
|
'title': title,
|
|
'body': body,
|
|
},
|
|
'data': {k: str(v) for k, v in (data or {}).items()},
|
|
'android': {
|
|
'priority': 'high',
|
|
'notification': {
|
|
'title': title,
|
|
'body': body,
|
|
# 'sound': 'incoming_call_sound',
|
|
'color': '#06EEBD',
|
|
# 'channel_id': 'incoming_call_channel',
|
|
'visibility': 'public',
|
|
},
|
|
},
|
|
}
|
|
}
|
|
# Send the POST request to FCM API
|
|
print(f'=========(send-notif)===******')
|
|
response = requests.post(FCM_URL, headers=headers, json=payload)
|
|
if response.status_code == 200:
|
|
logger.warning(f'Successfully sent message: {response.json()}')
|
|
responses.append(response.json())
|
|
else:
|
|
responses.append({'status': 'error', 'message': ""})
|
|
logger.error(f'Failed to send message notif')
|
|
|
|
return responses
|
|
|
|
|
|
|
|
@shared_task
|
|
def send_otp_code(phone_number, code):
|
|
BASE_URL_SERVICE = "https://console.melipayamak.com/api/send/simple/"
|
|
|
|
phone_number = str(phone_number)
|
|
code = str(code)
|
|
print(code)
|
|
data = {'from': '50004001410202', 'to': phone_number, 'text': code}
|
|
response = requests.post(f'{BASE_URL_SERVICE}{settings.OTP_SERIVCE_KEY}',
|
|
json=data)
|
|
|
|
print(response.json())
|
|
|
|
|
|
def send_otp_code_whatsapp(phone_number, code):
|
|
phone = phone_number
|
|
if phone.startswith('0'):
|
|
phone = phone[1:]
|
|
phone = '98' + phone
|
|
|
|
urls = [
|
|
"https://7103.api.greenapi.com/waInstance7103107557/sendMessage/dcc7cc469e274389aa3ea4d6dae9d4d126b8b07a09be41c28e",
|
|
"https://7103.api.greenapi.com/waInstance7103109151/sendMessage/ed9cbea884cc49fd8032862f1bceca2074f373540dca483382",
|
|
"https://7103.api.greenapi.com/waInstance7103109158/sendMessage/92d032caca1541799a4623cfcc86f449ea7f3205b30848eeab",
|
|
"https://7103.api.greenapi.com/waInstance7103109163/sendMessage/d31a08b5816c432daa6e256e181274d1d334e4256d3c4555a7",
|
|
|
|
]
|
|
payload = {
|
|
"chatId": f"{phone}@c.us",
|
|
"message": f"Habib App --aqila-- {code}"
|
|
}
|
|
headers = {
|
|
'Content-Type': 'application/json'
|
|
}
|
|
|
|
for url in urls:
|
|
response = requests.request("POST", url=url, headers=headers, data=json.dumps(payload))
|
|
response.encoding = 'utf-8'
|
|
response_data = response.json()
|
|
|
|
invoke_status = response_data.get('invokeStatus', {})
|
|
status = invoke_status.get('status', '')
|
|
|
|
print(f'>>>>>>>> {response_data}')
|
|
print(f"Response: {status}")
|
|
|
|
if status != "QUOTE_ALLOWED":
|
|
print("OTP sent successfully.")
|
|
break
|
|
else:
|
|
print("QUOTE_ALLOWED error, trying next URL...")
|
|
time.sleep(2)
|
|
|
|
|
|
@shared_task
|
|
def send_resend_email_task(recipient_list, subject, html_content):
|
|
"""
|
|
Sends an email using Resend API.
|
|
"""
|
|
if not settings.RESEND_API_KEY:
|
|
logger.error("RESEND_API_KEY is not set in settings.")
|
|
return False
|
|
|
|
url = "https://api.resend.com/emails"
|
|
headers = {
|
|
"Authorization": f"Bearer {settings.RESEND_API_KEY}",
|
|
"Content-Type": "application/json",
|
|
}
|
|
|
|
payload = {
|
|
"from": settings.RESEND_FROM_EMAIL,
|
|
"to": recipient_list,
|
|
"subject": subject,
|
|
"html": html_content,
|
|
}
|
|
|
|
try:
|
|
response = requests.post(url, headers=headers, json=payload)
|
|
response.raise_for_status()
|
|
logger.info(f"Email sent successfully to {recipient_list} via Resend.")
|
|
return response.json()
|
|
except Exception as e:
|
|
logger.error(f"Failed to send email via Resend: {str(e)}")
|
|
return False
|
|
|
|
|