MarseyWorld/files/helpers/alerts.py

348 lines
11 KiB
Python
Raw Normal View History

import json
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
from sys import stdout
import gevent
2022-05-04 23:09:46 +00:00
from flask import g
from pywebpush import webpush
2023-03-02 00:32:51 +00:00
import time
from sqlalchemy.sql import text, and_
from sqlalchemy.orm import load_only
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
2024-02-23 21:52:18 +00:00
from files.classes import Comment, Post, Notification, PushSubscription, Group, Mod
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
from .config.const import *
from .regex import *
[DO NOT MERGE] import detanglation (#442) * move Base definition to files.classes.__init__.py * fix ImportError * move userpage listing to users.py * don't import the app from classes * consts: set default values to avoid crashes consts: warn if the secret key is the default config value * card view: sneed (user db schema) * cloudflare: use DEFAULT_CONFIG_VALUE * const: set default values * decouple media.py from __main__ * pass database to avoid imports * import cleanup and import request not in const, but in the requests mega import * move asset_submissions site check to __init__ * asset submissions feature flag * flag * g.is_tor * don't import request where it's not needed * i think this is fine * mail: move to own routes and helper * wrappers * required wrappers move * unfuck wrappers a bit * move snappy quotes and marseys to stateful consts * marsify * :pepodrool: * fix missing import * import cache * ...and settings.py * and static.py * static needs cache * route * lmao all of the jinja shit was in feeds.py amazing * classes should only import what they need from flask * import Response * hdjbjdhbhjf * ... * dfdfdfdf * make get a non-required import * isort imports (mostly) * but actually * configs * reload config on import * fgfgfgfg * config * config * initialize snappy and test * cookie of doom debug * edfjnkf * xikscdfd * debug config * set session cookie domain, i think this fixes the can't login bug * sdfbgnhvfdsghbnjfbdvvfghnn * hrsfxgf * dump the entire config on a request * kyskyskyskyskyskyskyskyskys * duifhdskfjdfd * dfdfdfdfdfdfdfdfdfdfdfdf * dfdfdfdf * imoprt all of the consts beacuse fuck it * 😭 * dfdfdfdfdfdfsdasdf * print the entire session * rffdfdfjkfksj * fgbhffh * not the secret keys * minor bug fixes * be helpful in the warning * gfgfgfg * move warning lower * isort main imports (i hope this doesn't fuck something up) * test * session cookie domain redux * dfdfdfd * try only importing Flask * formkeys fix * y * :pepodrool: * route helper * remove before flight * dfdfdfdfdf * isort classes * isort helpers * move check_for_alts to routehelpers and also sort imports and get rid of unused ones * that previous commit but actkally * readd the cache in a dozen places they were implicitly imported * use g.is_tor instead of request.headers. bla bla bla * upgrade streamers to their own route file * get rid of unused imports in __main__ * fgfgf * don't pull in the entire ORM where we don't need it * features * explicit imports for the get helper * explicit imports for the get helper redux * testing allroutes * remove unused import * decouple flask from classes * syntax fix also remember these have side fx for some reason (why?) * move side effects out of the class * posts * testing on devrama * settings * reloading * settingssdsdsds * streamer features * site settings * testing settings on devrama * import * fix modlog * remove debug stuff * revert commit 67275b21ab6e2f2520819e84d10bfc1c746a15b6 * archiveorg to _archiveorg * skhudkfkjfd * fix cron for PCM * fix bugs that snekky wants me to * Fix call to realbody passing db, standardize kwarg * test * import check_for_alts from the right place * cloudflare * testing on devrama * fix cron i think * shadow properly * tasks * Remove print which will surely be annoying in prod. * v and create new session * use files.classes * make errors import little and fix rare 500 in /allow_nsfw * Revert "use files.classes" This reverts commit 98c10b876cf86ce058b7fb955cf1ec0bfb9996c6. * pass v to media functions rather than using g * fix * dfdfdfdfd * cleanup, py type checking is dumb so don't use it where it causes issues * Fix some merge bugs, add DEFAULT_RATELIMIT to main. * Fix imports on sqlalchemy expressions. * `from random import random` is an error. * Fix replies db param. * errors: fix missing import * fix rare 500: only send to GIFT_NOTIF_ID if it exists, and send them the right text * Fix signup formkey. * fix 2 500s * propagate db to submissions * fix replies * dfdfdfdf * Fix verifiedcolor. * is_manual * can't use getters outside of an app context * don't attempt to do gumroad on sites where it's not enabled * don't attempt to do gumraod on sites's where it's unnecessary * Revert "don't attempt to do gumroad on sites where it's not enabled" This reverts commit 6f8a6331878655492dfaf1907b27f8be513c14d3. * fix 500 * validate media type Co-authored-by: TLSM <duolsm@outlook.com>
2022-11-15 09:19:08 +00:00
from .sanitize import *
from .slurs_and_profanities import censor_slurs_profanities
2022-05-04 23:09:46 +00:00
def create_comment(text_html):
new_comment = Comment(author_id=AUTOJANNY_ID,
parent_post=None,
body_html=text_html,
distinguished=True,
is_bot=True)
2023-03-16 06:27:58 +00:00
g.db.add(new_comment)
g.db.flush()
2022-05-04 23:09:46 +00:00
new_comment.top_comment_id = new_comment.id
return new_comment.id
def send_repeatable_notification(uid, text, only_repeatable_after_1week=False):
2023-05-12 22:29:34 +00:00
if uid in BOT_IDs: return
2022-05-28 02:20:31 +00:00
2023-10-05 07:38:35 +00:00
if hasattr(g, 'v') and g.v and g.v.shadowbanned and g.db.query(User.admin_level).filter_by(id=uid).one()[0] < PERMS['USER_SHADOWBAN']:
return
2023-02-07 03:31:49 +00:00
text_html = sanitize(text, blackjack="notification")
2022-05-04 23:09:46 +00:00
existing_comments = g.db.query(Comment.id).filter_by(author_id=AUTOJANNY_ID, parent_post=None, body_html=text_html, is_bot=True).order_by(Comment.id).all()
2022-05-04 23:09:46 +00:00
existing_notif = None
for c in existing_comments:
existing_notif = g.db.query(Notification).filter_by(user_id=uid, comment_id=c.id).one_or_none()
if not existing_notif:
notif = Notification(comment_id=c.id, user_id=uid)
2023-03-16 06:27:58 +00:00
g.db.add(notif)
2023-08-23 10:42:25 +00:00
push_notif({uid}, 'New notification', text, f'{SITE_FULL}/notification/{c.id}')
2023-11-15 22:23:31 +00:00
return notif
2022-05-04 23:09:46 +00:00
one_week_ago = time.time() - 604800
if only_repeatable_after_1week and existing_notif and existing_notif.created_utc > one_week_ago:
return
cid = create_comment(text_html)
2022-05-04 23:09:46 +00:00
notif = Notification(comment_id=cid, user_id=uid)
2023-03-16 06:27:58 +00:00
g.db.add(notif)
2022-05-04 23:09:46 +00:00
2023-08-23 10:42:25 +00:00
push_notif({uid}, 'New notification', text, f'{SITE_FULL}/notification/{cid}')
2023-10-11 20:01:57 +00:00
return notif
2022-05-04 23:09:46 +00:00
def send_notification(uid, text):
send_repeatable_notification(uid, text, only_repeatable_after_1week=True)
2022-05-04 23:09:46 +00:00
def notif_comment(text):
2022-05-04 23:09:46 +00:00
2023-02-07 03:31:49 +00:00
text_html = sanitize(text, blackjack="notification")
2022-05-04 23:09:46 +00:00
2023-03-16 06:27:58 +00:00
existing = g.db.query(Comment.id).filter(
Comment.author_id == AUTOJANNY_ID,
Comment.parent_post == None,
Comment.body_html == text_html,
Comment.is_bot == True,
).order_by(Comment.id).all()
if len(existing) > 1:
to_delete = [x[0] for x in existing[1:]]
for n in g.db.query(Notification).filter(Notification.comment_id.in_(to_delete)):
g.db.delete(n)
for c in g.db.query(Comment).filter(Comment.id.in_(to_delete)):
2023-03-16 06:27:58 +00:00
g.db.delete(c)
return existing[0][0]
elif existing:
return existing[0][0]
else:
return create_comment(text_html)
2022-05-04 23:09:46 +00:00
2024-01-14 08:54:01 +00:00
def notif_comment_mention(p):
2023-10-15 13:15:39 +00:00
if p.ghost:
author_link = '@👻'
else:
author_link = f'<a href="/id/{p.author_id}"><img loading="lazy" src="/pp/{p.author_id}">@{p.author_name}</a>'
2023-10-15 13:15:39 +00:00
2024-01-07 00:29:20 +00:00
text = f'@{p.author_name} has mentioned you: {p.title}'
2023-02-24 02:28:10 +00:00
2023-07-03 23:43:29 +00:00
search_html = f'%</a> has mentioned you: <a href="/post/{p.id}"%'
2022-05-04 23:09:46 +00:00
2024-02-11 11:24:43 +00:00
existing = g.db.query(Comment.id).filter(
Comment.author_id == AUTOJANNY_ID,
Comment.parent_post == None,
Comment.body_html.like(search_html),
).first()
2023-01-01 11:36:20 +00:00
2023-02-24 02:28:10 +00:00
if existing: return existing[0], text
2022-05-04 23:09:46 +00:00
else:
2024-01-07 00:29:20 +00:00
text_html = f'{author_link} has mentioned you: <a href="/post/{p.id}">{p.title_html}</a>'
if p.hole: text_html += f" in <a href='/h/{p.hole}'>/h/{p.hole}"
return create_comment(text_html), text
2022-05-04 23:09:46 +00:00
def add_notif(cid, uid, text, pushnotif_url='', check_existing=True):
2023-05-12 22:29:34 +00:00
if uid in BOT_IDs: return
2022-05-28 02:20:31 +00:00
if hasattr(g, 'v') and g.v and g.v.shadowbanned and g.db.query(User.admin_level).filter_by(id=uid).one()[0] < PERMS['USER_SHADOWBAN']:
return
if check_existing:
existing = g.db.query(Notification.user_id).filter_by(comment_id=cid, user_id=uid).one_or_none()
if existing: return
2022-05-04 23:09:46 +00:00
notif = Notification(comment_id=cid, user_id=uid)
g.db.add(notif)
if not pushnotif_url:
pushnotif_url = f'{SITE_FULL}/notification/{cid}'
if ' has mentioned you: [' in text:
text = text.split(':')[0] + '!'
2024-02-10 15:34:45 +00:00
push_notif({uid}, 'New notification', text, pushnotif_url)
2023-02-24 02:28:10 +00:00
2022-05-04 23:09:46 +00:00
def NOTIFY_USERS(text, v, oldtext=None, ghost=False, obj=None, followers_ping=True, commenters_ping_post_id=None, charge=True):
2022-07-29 19:55:12 +00:00
# Restrict young accounts from generating notifications
if v.age < NOTIFICATION_SPAM_AGE_THRESHOLD:
return set()
2023-02-18 16:58:59 +00:00
text = text.lower()
if oldtext:
oldtext = oldtext.lower()
2022-05-04 23:09:46 +00:00
notify_users = set()
2023-02-18 16:58:59 +00:00
criteria = (Notification.user_id == User.id, Notification.read == False)
2024-04-11 10:25:22 +00:00
keyword_users = g.db.query(User.id, User.keyword_notifs).outerjoin(Notification, and_(*criteria)).group_by(User.id, User.keyword_notifs).having(func.count(Notification.user_id) < 100).filter(User.keyword_notifs != None, User.patron >= 5)
2024-03-02 10:14:26 +00:00
for uid, keyword_notifs in keyword_users:
for word in keyword_notifs.lower().split('\n'):
2024-03-02 12:44:37 +00:00
if not word: continue
if word in text:
2024-03-02 10:14:26 +00:00
notify_users.add(uid)
names = set(m.group(1) for m in mention_regex.finditer(text))
2023-03-11 05:07:10 +00:00
if oldtext:
oldnames = set(m.group(1) for m in mention_regex.finditer(oldtext))
names = names - oldnames
2023-03-01 20:28:34 +00:00
user_ids = get_users(names, ids_only=True, graceful=True)
notify_users.update(user_ids)
2022-05-04 23:09:46 +00:00
2024-04-10 03:09:19 +00:00
if SITE_NAME == "WPD" and (('daisy' in text and 'destruction' in text) or ('kill myself' in text and obj and isinstance(obj, Post))):
admin_ids = [x[0] for x in g.db.query(User.id).filter(User.admin_level >= PERMS['NOTIFICATIONS_SPECIFIC_WPD_COMMENTS'], User.id != AEVANN_ID)]
2022-08-18 09:52:37 +00:00
notify_users.update(admin_ids)
if FEATURES['PING_GROUPS']:
cost = 0
2024-03-02 17:02:05 +00:00
cost_groups = []
coin_receivers = set()
2023-08-20 00:58:58 +00:00
for i in group_mention_regex.finditer(text):
if oldtext and re.search(f'(?<![:/\w])!{i.group(1)}($|[^\w-])', oldtext):
continue
if re.search(f'^>.*?(?<![:/\w])!{i.group(1)}', text):
continue
if i.group(1) == 'focusgroup' and not v.admin_level:
2024-03-27 14:17:24 +00:00
abort(403, "Only admins can mention !focusgroup")
if i.group(1) == 'everyone':
if charge:
cost = g.db.query(User).count() * 5
if cost > v.coins + v.marseybux:
abort(403, f"You need {cost} currency to mention these ping groups!")
2024-03-02 17:02:05 +00:00
2024-03-02 17:24:07 +00:00
reason = f"Group pinging cost (<code>!everyone</code>)"
2024-03-02 17:02:05 +00:00
if obj:
reason += f" on {obj.textlink}"
v.charge_account('coins/marseybux', cost, reason)
if obj:
obj.ping_cost += cost
return 'everyone'
2023-07-21 14:27:45 +00:00
elif i.group(1) == 'jannies':
group = None
2024-03-02 10:20:29 +00:00
member_ids = set(x[0] for x in g.db.query(User.id).filter(User.admin_level > 0))
elif i.group(1) == 'holejannies':
if not get_obj_hole(obj):
abort(403, "!holejannies can only be used inside holes!")
group = None
member_ids = set(x[0] for x in g.db.query(Mod.user_id).filter_by(hole=obj.hole))
2023-08-11 13:34:56 +00:00
elif i.group(1) == 'followers':
2023-08-11 13:38:49 +00:00
if not followers_ping:
abort(403, f"You can't use !followers in posts!")
2023-08-11 13:34:56 +00:00
group = None
member_ids = set(x[0] for x in g.db.query(Follow.user_id).filter_by(target_id=v.id))
elif i.group(1) == 'commenters':
if not commenters_ping_post_id:
abort(403, "You can only use !commenters in comments made under posts!")
group = None
member_ids = set(x[0] for x in g.db.query(User.id).join(Comment, Comment.author_id == User.id).filter(Comment.parent_post == commenters_ping_post_id)) - {v.id}
else:
2023-03-16 06:27:58 +00:00
group = g.db.get(Group, i.group(1))
if not group: continue
2023-07-21 14:27:45 +00:00
member_ids = group.member_ids
members = member_ids - notify_users - BOT_IDs - v.all_twoway_blocks - v.muters
2023-05-05 21:45:25 +00:00
2023-07-21 14:27:45 +00:00
notify_users.update(members)
if charge:
realghost = ghost and i.group(1) != 'ghosts'
if (realghost or v.id not in member_ids) and i.group(1) != 'followers':
if group and group.name == 'verifiedrich':
abort(403, f"Only !verifiedrich members can mention it!")
cost += len(members) * 5
cost_groups.append(i.group(1))
if cost > v.coins + v.marseybux:
abort(403, f"You need {cost} currency to mention these ping groups!")
if i.group(1) in {'biofoids','neofoids','jannies'}:
coin_receivers.update(member_ids)
if charge:
if cost:
2024-03-02 17:24:07 +00:00
reason = f"Group pinging cost (<code>!" + "</code>, <code>!".join(cost_groups) + "</code>)"
2024-03-02 17:02:05 +00:00
if obj:
reason += f" on {obj.textlink}"
v.charge_account('coins/marseybux', cost, reason)
if obj:
obj.ping_cost += cost
if coin_receivers:
g.db.query(User).options(load_only(User.id)).filter(User.id.in_(coin_receivers)).update({ User.coins: User.coins + 5 })
2023-08-31 10:46:07 +00:00
if len(notify_users) > 400 and v.admin_level < PERMS['POST_COMMENT_INFINITE_PINGS']:
abort(403, "You can only notify a maximum of 400 users.")
2023-08-20 00:58:58 +00:00
2023-10-29 15:53:05 +00:00
if v.shadowbanned or (obj and obj.is_banned):
notify_users = set(x[0] for x in g.db.query(User.id).filter(User.id.in_(notify_users), User.admin_level >= PERMS['USER_SHADOWBAN']).all())
return notify_users - BOT_IDs - {v.id, 0} - v.all_twoway_blocks - v.muters
2022-06-10 12:28:46 +00:00
2023-02-24 03:00:22 +00:00
def push_notif(uids, title, body, url_or_comment):
2023-08-20 08:17:38 +00:00
if hasattr(g, 'v') and g.v and g.v.shadowbanned:
2023-10-05 10:05:20 +00:00
uids = [x[0] for x in g.db.query(User.id).filter(User.id.in_(uids), User.admin_level >= PERMS['USER_SHADOWBAN']).all()]
if not uids:
return
if VAPID_PUBLIC_KEY == DEFAULT_CONFIG_VALUE:
return
2023-02-24 03:00:22 +00:00
if isinstance(url_or_comment, Comment):
c = url_or_comment
if c.is_banned: return
2023-02-24 03:00:22 +00:00
if c.wall_user_id:
url = f'{SITE_FULL}/@{c.wall_user.username}/wall/comment/{c.id}?read=true#context'
2023-02-24 01:56:46 +00:00
else:
2023-02-24 03:00:22 +00:00
url = f'{SITE_FULL}/comment/{c.id}?read=true#context'
else:
url = url_or_comment
2023-02-24 01:56:46 +00:00
if len(body) > PUSH_NOTIF_LIMIT:
body = body[:PUSH_NOTIF_LIMIT] + "..."
body = censor_slurs_profanities(body, None, True)
2023-03-16 06:27:58 +00:00
subscriptions = g.db.query(PushSubscription.subscription_json).filter(PushSubscription.user_id.in_(uids)).all()
2022-12-02 23:25:48 +00:00
subscriptions = [x[0] for x in subscriptions]
gevent.spawn(_push_notif_thread, subscriptions, title, body, url)
2022-12-02 23:25:48 +00:00
def _push_notif_thread(subscriptions, title, body, url):
for subscription in subscriptions:
2022-12-02 23:25:48 +00:00
try:
2023-07-26 12:20:32 +00:00
webpush(
2022-12-02 23:25:48 +00:00
subscription_info=json.loads(subscription),
data=json.dumps({
"title": title,
"body": body,
'url': url,
2024-03-05 18:40:55 +00:00
'icon': f'{SITE_FULL}/icon.webp?x=8',
2022-12-02 23:25:48 +00:00
}),
vapid_private_key=VAPID_PRIVATE_KEY,
vapid_claims={"sub": f"mailto:{EMAIL}"}
)
except: continue
2023-03-02 00:32:51 +00:00
def alert_everyone(cid):
cid = int(cid)
t = int(time.time())
_everyone_query = text(f"""
insert into notifications
select id, {cid}, false, {t} from users
on conflict do nothing;""")
2023-03-16 06:27:58 +00:00
g.db.execute(_everyone_query)
2024-02-06 22:04:43 +00:00
def alert_admins(body):
body_html = sanitize(body, blackjack="admin alert")
new_comment = Comment(author_id=AUTOJANNY_ID,
parent_post=None,
level=1,
body_html=body_html,
sentto=MODMAIL_ID,
distinguished=True,
is_bot=True
)
g.db.add(new_comment)
g.db.flush()
new_comment.top_comment_id = new_comment.id
2024-02-10 15:34:45 +00:00
def alert_active_users(body, vid, extra_criteria):
body_html = sanitize(body, blackjack="notification")
cid = create_comment(body_html)
t = time.time() - 604800
notified_users = [x[0] for x in g.db.query(User.id).filter(
User.last_active > t,
2024-02-10 15:34:45 +00:00
User.id != vid,
extra_criteria,
)]
for uid in notified_users:
add_notif(cid, uid, body, check_existing=False)