2022-10-13 07:27:56 +00:00
|
|
|
import json
|
|
|
|
import requests
|
2024-03-31 23:22:27 +00:00
|
|
|
import gevent
|
2024-03-30 22:20:23 +00:00
|
|
|
from files.helpers.config.const import *
|
2024-03-31 23:22:27 +00:00
|
|
|
from files.helpers.media import *
|
2024-03-30 22:17:55 +00:00
|
|
|
|
2022-10-13 07:27:56 +00:00
|
|
|
CLOUDFLARE_API_URL = "https://api.cloudflare.com/client/v4"
|
|
|
|
CLOUDFLARE_REQUEST_TIMEOUT_SECS = 5
|
|
|
|
|
2022-11-15 09:19:08 +00:00
|
|
|
CLOUDFLARE_AVAILABLE = CF_ZONE and CF_ZONE != DEFAULT_CONFIG_VALUE
|
2022-11-09 05:35:24 +00:00
|
|
|
|
2023-07-30 00:42:06 +00:00
|
|
|
def _request_from_cloudflare(url, method, post_data_str):
|
2022-11-09 05:35:24 +00:00
|
|
|
if not CLOUDFLARE_AVAILABLE: return False
|
2023-10-18 21:14:59 +00:00
|
|
|
try:
|
|
|
|
res = str(requests.request(method, f"{CLOUDFLARE_API_URL}/zones/{CF_ZONE}/{url}", headers=CF_HEADERS, data=post_data_str, timeout=CLOUDFLARE_REQUEST_TIMEOUT_SECS))
|
|
|
|
except Exception as e:
|
|
|
|
print(e, flush=True)
|
|
|
|
return False
|
2022-10-28 23:39:31 +00:00
|
|
|
return res == "<Response [200]>"
|
2022-10-13 07:27:56 +00:00
|
|
|
|
2023-07-30 00:42:06 +00:00
|
|
|
def set_security_level(under_attack="high"):
|
2022-10-28 23:39:31 +00:00
|
|
|
return _request_from_cloudflare("settings/security_level", "PATCH", f'{{"value":"{under_attack}"}}')
|
2022-10-13 07:27:56 +00:00
|
|
|
|
2023-07-30 00:42:06 +00:00
|
|
|
def clear_entire_cache():
|
2022-11-08 08:05:43 +00:00
|
|
|
return _request_from_cloudflare("purge_cache", "POST", '{"purge_everything":true}')
|
2022-10-13 07:27:56 +00:00
|
|
|
|
2023-09-15 00:07:17 +00:00
|
|
|
def purge_files_in_cloudflare_cache(files):
|
2022-11-09 05:35:24 +00:00
|
|
|
if not CLOUDFLARE_AVAILABLE: return False
|
2022-10-28 23:39:31 +00:00
|
|
|
if isinstance(files, str):
|
|
|
|
files = [files]
|
2024-03-30 22:17:55 +00:00
|
|
|
|
2022-10-28 23:39:31 +00:00
|
|
|
post_data = {"files": files}
|
|
|
|
res = None
|
|
|
|
try:
|
|
|
|
res = requests.post(f'{CLOUDFLARE_API_URL}/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS, data=json.dumps(post_data), timeout=CLOUDFLARE_REQUEST_TIMEOUT_SECS)
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
return res == "<Response [200]>"
|