forked from rDrama/rDrama
create cloudflare helper
parent
e7da195645
commit
c56e45aa57
|
@ -0,0 +1,42 @@
|
||||||
|
import json
|
||||||
|
from typing import List, Union, Optional
|
||||||
|
from files.helpers.const import *
|
||||||
|
import requests
|
||||||
|
|
||||||
|
CLOUDFLARE_API_URL = "https://api.cloudflare.com/client/v4"
|
||||||
|
CLOUDFLARE_REQUEST_TIMEOUT_SECS = 5
|
||||||
|
DEFAULT_CLOUDFLARE_ZONE = 'blahblahblah'
|
||||||
|
|
||||||
|
def _request_from_cloudflare(url:str, method:str, post_data_str) -> bool:
|
||||||
|
if CF_ZONE == DEFAULT_CLOUDFLARE_ZONE: return False
|
||||||
|
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:
|
||||||
|
return False
|
||||||
|
return res == "<Response [200]>"
|
||||||
|
|
||||||
|
def get_security_level() -> Optional[str]:
|
||||||
|
res = None
|
||||||
|
try:
|
||||||
|
res = requests.get(f'{CLOUDFLARE_API_URL}/zones/{CF_ZONE}/settings/security_level', headers=CF_HEADERS, timeout=5).json()['result']['value']
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
return res
|
||||||
|
|
||||||
|
def set_security_level(under_attack="high") -> bool:
|
||||||
|
return _request_from_cloudflare("settings/security_level", "PATCH", f'{{"value":"{under_attack}"}}')
|
||||||
|
|
||||||
|
def purge_entire_cache() -> bool:
|
||||||
|
return _request_from_cloudflare("purge_cache", "POST", '{"purge_everything":true}')
|
||||||
|
|
||||||
|
def purge_files_in_cache(files:Union[List[str],str]) -> bool:
|
||||||
|
if CF_ZONE == DEFAULT_CLOUDFLARE_ZONE: return False
|
||||||
|
if isinstance(files, str):
|
||||||
|
files = [files]
|
||||||
|
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]>"
|
|
@ -11,6 +11,7 @@ import gevent
|
||||||
import imagehash
|
import imagehash
|
||||||
from shutil import copyfile
|
from shutil import copyfile
|
||||||
from files.classes.media import *
|
from files.classes.media import *
|
||||||
|
from files.helpers.cloudflare import purge_files_in_cache
|
||||||
from files.__main__ import db_session
|
from files.__main__ import db_session
|
||||||
|
|
||||||
def process_files():
|
def process_files():
|
||||||
|
@ -66,9 +67,7 @@ def webm_to_mp4(old, new, vid):
|
||||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "warning", "-nostats", "-threads:v", "1", "-i", old, "-map_metadata", "-1", tmp], check=True, stderr=subprocess.STDOUT)
|
subprocess.run(["ffmpeg", "-y", "-loglevel", "warning", "-nostats", "-threads:v", "1", "-i", old, "-map_metadata", "-1", tmp], check=True, stderr=subprocess.STDOUT)
|
||||||
os.replace(tmp, new)
|
os.replace(tmp, new)
|
||||||
os.remove(old)
|
os.remove(old)
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
purge_files_in_cache(f"{SITE_FULL}{new}")
|
||||||
data=f'{{"files": ["{SITE_FULL}{new}"]}}', timeout=5)
|
|
||||||
|
|
||||||
db = db_session()
|
db = db_session()
|
||||||
|
|
||||||
media = db.query(Media).filter_by(filename=new, kind='video').one_or_none()
|
media = db.query(Media).filter_by(filename=new, kind='video').one_or_none()
|
||||||
|
|
|
@ -11,6 +11,7 @@ from files.helpers.get import *
|
||||||
from files.helpers.media import *
|
from files.helpers.media import *
|
||||||
from files.helpers.const import *
|
from files.helpers.const import *
|
||||||
from files.helpers.actions import *
|
from files.helpers.actions import *
|
||||||
|
from files.helpers.cloudflare import *
|
||||||
from files.classes import *
|
from files.classes import *
|
||||||
from flask import *
|
from flask import *
|
||||||
from files.__main__ import app, cache, limiter
|
from files.__main__ import app, cache, limiter
|
||||||
|
@ -426,9 +427,7 @@ def admin_home(v):
|
||||||
under_attack = False
|
under_attack = False
|
||||||
|
|
||||||
if v.admin_level >= PERMS['SITE_SETTINGS_UNDER_ATTACK']:
|
if v.admin_level >= PERMS['SITE_SETTINGS_UNDER_ATTACK']:
|
||||||
if CF_ZONE == 'blahblahblah': response = 'high'
|
under_attack = (get_security_level() or 'high') == 'under_attack'
|
||||||
else: response = requests.get(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/settings/security_level', headers=CF_HEADERS, timeout=5).json()['result']['value']
|
|
||||||
under_attack = response == 'under_attack'
|
|
||||||
|
|
||||||
gitref = admin_git_head()
|
gitref = admin_git_head()
|
||||||
|
|
||||||
|
@ -479,44 +478,33 @@ def purge_cache(v):
|
||||||
online = cache.get(ONLINE_STR)
|
online = cache.get(ONLINE_STR)
|
||||||
cache.clear()
|
cache.clear()
|
||||||
cache.set(ONLINE_STR, online)
|
cache.set(ONLINE_STR, online)
|
||||||
|
if not purge_entire_cache():
|
||||||
response = str(requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS, data='{"purge_everything":true}', timeout=5))
|
abort(400, 'Failed to purge cache')
|
||||||
|
|
||||||
ma = ModAction(
|
ma = ModAction(
|
||||||
kind="purge_cache",
|
kind="purge_cache",
|
||||||
user_id=v.id
|
user_id=v.id
|
||||||
)
|
)
|
||||||
g.db.add(ma)
|
g.db.add(ma)
|
||||||
|
return {"message": "Cache purged!"}
|
||||||
if response == "<Response [200]>": return {"message": "Cache purged!"}
|
|
||||||
abort(400, 'Failed to purge cache.')
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/admin/under_attack")
|
@app.post("/admin/under_attack")
|
||||||
@admin_level_required(PERMS['SITE_SETTINGS_UNDER_ATTACK'])
|
@admin_level_required(PERMS['SITE_SETTINGS_UNDER_ATTACK'])
|
||||||
def under_attack(v):
|
def under_attack(v):
|
||||||
response = requests.get(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/settings/security_level', headers=CF_HEADERS, timeout=5).json()['result']['value']
|
response = get_security_level()
|
||||||
|
if not response:
|
||||||
if response == 'under_attack':
|
abort(400, 'Could not retrieve the current security level')
|
||||||
ma = ModAction(
|
old_under_attack_mode = response == 'under_attack'
|
||||||
kind="disable_under_attack",
|
enable_disable_str = 'disable' if old_under_attack_mode else 'enable'
|
||||||
user_id=v.id,
|
new_security_level = 'high' if old_under_attack_mode else 'under_attack'
|
||||||
)
|
if not set_security_level(new_security_level):
|
||||||
g.db.add(ma)
|
abort(400, f'Failed to {enable_disable_str} under attack mode')
|
||||||
|
ma = ModAction(
|
||||||
response = str(requests.patch(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/settings/security_level', headers=CF_HEADERS, data='{"value":"high"}', timeout=5))
|
kind=f"{enable_disable_str}_under_attack",
|
||||||
if response == "<Response [200]>": return {"message": "Under attack mode disabled!"}
|
user_id=v.id,
|
||||||
abort(400, "Failed to disable under attack mode.")
|
)
|
||||||
else:
|
g.db.add(ma)
|
||||||
ma = ModAction(
|
return {"message": f"Under attack mode {enable_disable_str}!"}
|
||||||
kind="enable_under_attack",
|
|
||||||
user_id=v.id,
|
|
||||||
)
|
|
||||||
g.db.add(ma)
|
|
||||||
|
|
||||||
response = str(requests.patch(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/settings/security_level', headers=CF_HEADERS, data='{"value":"under_attack"}', timeout=5))
|
|
||||||
if response == "<Response [200]>": return {"message": "Under attack mode enabled!"}
|
|
||||||
abort(400, "Failed to enable under attack mode.")
|
|
||||||
|
|
||||||
@app.get("/admin/badge_grant")
|
@app.get("/admin/badge_grant")
|
||||||
@admin_level_required(PERMS['USER_BADGES'])
|
@admin_level_required(PERMS['USER_BADGES'])
|
||||||
|
@ -1142,10 +1130,7 @@ def remove_post(post_id, v):
|
||||||
|
|
||||||
v.coins += 1
|
v.coins += 1
|
||||||
g.db.add(v)
|
g.db.add(v)
|
||||||
|
purge_files_in_cache(f"https://{SITE}/logged_out")
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
|
||||||
data=f'{{"files": ["https://{SITE}/logged_out"]}}', timeout=5)
|
|
||||||
|
|
||||||
return {"message": "Post removed!"}
|
return {"message": "Post removed!"}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -132,9 +132,7 @@ if SITE not in ('pcmemes.net', 'watchpeopledie.co'):
|
||||||
badge_grant(badge_id=16, user=author)
|
badge_grant(badge_id=16, user=author)
|
||||||
else:
|
else:
|
||||||
badge_grant(badge_id=17, user=author)
|
badge_grant(badge_id=17, user=author)
|
||||||
|
purge_files_in_cache(f"https://{SITE}/e/{marsey.name}/webp")
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
|
||||||
data=f'{{"files": ["https://{SITE}/e/{marsey.name}.webp"]}}', timeout=5)
|
|
||||||
cache.delete_memoized(marsey_list)
|
cache.delete_memoized(marsey_list)
|
||||||
|
|
||||||
|
|
||||||
|
@ -389,9 +387,7 @@ if SITE not in ('pcmemes.net', 'watchpeopledie.co'):
|
||||||
filename = f"files/assets/images/emojis/{name}.webp"
|
filename = f"files/assets/images/emojis/{name}.webp"
|
||||||
copyfile(new_path, filename)
|
copyfile(new_path, filename)
|
||||||
process_image(filename, resize=200, trim=True)
|
process_image(filename, resize=200, trim=True)
|
||||||
|
purge_files_in_cache([f"https://{SITE}/e/{name}.webp", f"https://{SITE}/assets/images/emojis/{name}.webp", f"https://{SITE}/asset_submissions/marseys/original/{name}.{format}"])
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
|
||||||
data=f'{{"files": ["https://{SITE}/e/{name}.webp", "https://{SITE}/assets/images/emojis/{name}.webp", "https://{SITE}/asset_submissions/marseys/original/{name}.{format}"]}}', timeout=5)
|
|
||||||
|
|
||||||
ma = ModAction(
|
ma = ModAction(
|
||||||
kind="update_marsey",
|
kind="update_marsey",
|
||||||
|
@ -458,10 +454,7 @@ if SITE not in ('pcmemes.net', 'watchpeopledie.co'):
|
||||||
filename = f"files/assets/images/hats/{name}.webp"
|
filename = f"files/assets/images/hats/{name}.webp"
|
||||||
copyfile(new_path, filename)
|
copyfile(new_path, filename)
|
||||||
process_image(filename)
|
process_image(filename)
|
||||||
|
purge_files_in_cache([f"https://{SITE}/i/hats/{name}.webp", f"https://{SITE}/assets/images/hats/{name}.webp", f"https://{SITE}/asset_submissions/hats/original/{name}.{format}"])
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
|
||||||
data=f'{{"files": ["https://{SITE}/i/hats/{name}.webp", "https://{SITE}/assets/images/hats/{name}.webp", "https://{SITE}/asset_submissions/hats/original/{name}.{format}"]}}', timeout=5)
|
|
||||||
|
|
||||||
ma = ModAction(
|
ma = ModAction(
|
||||||
kind="update_hat",
|
kind="update_hat",
|
||||||
user_id=v.id,
|
user_id=v.id,
|
||||||
|
|
|
@ -215,8 +215,7 @@ def comment(v):
|
||||||
filename = f'files/assets/images/badges/{badge.id}.webp'
|
filename = f'files/assets/images/badges/{badge.id}.webp'
|
||||||
copyfile(oldname, filename)
|
copyfile(oldname, filename)
|
||||||
process_image(filename, resize=300)
|
process_image(filename, resize=300)
|
||||||
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS,
|
purge_files_in_cache(f"https://{SITE}/assets/images/badges/{badge.id}.webp")
|
||||||
data=f'{{"files": ["https://{SITE}/assets/images/badges/{badge.id}.webp"]}}', timeout=5)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
abort(400, str(e))
|
abort(400, str(e))
|
||||||
body += f"\n\n![]({image})"
|
body += f"\n\n![]({image})"
|
||||||
|
|
Loading…
Reference in New Issue