diff --git a/Dockerfile b/Dockerfile index d77b183d4..67649f5ae 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ FROM python:3.10 AS base ARG DEBIAN_FRONTEND=noninteractive -RUN apt update && apt -y upgrade && apt install -y supervisor ffmpeg +RUN apt update && apt -y upgrade && apt install -y supervisor # we'll end up blowing away this directory via docker-compose WORKDIR /service @@ -13,7 +13,7 @@ COPY poetry.lock . RUN pip install 'poetry==1.2.2' RUN poetry config virtualenvs.create false && poetry install -RUN mkdir /images && mkdir /songs +RUN mkdir /images EXPOSE 80/tcp @@ -24,7 +24,7 @@ ENV FLASK_APP=files/cli:app # Release container FROM base AS release -COPY supervisord.conf.release /etc/supervisord.conf +COPY bootstrap/supervisord.conf.release /etc/supervisord.conf CMD [ "/usr/bin/supervisord", "-c", "/etc/supervisord.conf" ] @@ -36,7 +36,7 @@ FROM release AS dev COPY thirdparty/sqlalchemy-easy-profile sqlalchemy-easy-profile RUN cd sqlalchemy-easy-profile && python3 setup.py install -COPY supervisord.conf.dev /etc/supervisord.conf +COPY bootstrap/supervisord.conf.dev /etc/supervisord.conf CMD [ "/usr/bin/supervisord", "-c", "/etc/supervisord.conf" ] diff --git a/schema.sql b/bootstrap/original-schema.sql similarity index 100% rename from schema.sql rename to bootstrap/original-schema.sql diff --git a/seed-db.sql b/bootstrap/original-seed-db.sql similarity index 100% rename from seed-db.sql rename to bootstrap/original-seed-db.sql diff --git a/env b/bootstrap/site_env similarity index 97% rename from env rename to bootstrap/site_env index 9fe97684c..66ffea61b 100644 --- a/env +++ b/bootstrap/site_env @@ -8,7 +8,6 @@ HCAPTCHA_SECRET=blahblahblah YOUTUBE_KEY=blahblahblah PUSHER_ID=blahblahblah PUSHER_KEY=blahblahblah -IMGUR_KEY=blahblahblah SPAM_SIMILARITY_THRESHOLD=0.5 SPAM_URL_SIMILARITY_THRESHOLD=0.1 SPAM_SIMILAR_COUNT_THRESHOLD=10 @@ -31,6 +30,7 @@ MENTION_LIMIT=100 MULTIMEDIA_EMBEDDING_ENABLED=False RESULTS_PER_PAGE_COMMENTS=200 SCORE_HIDING_TIME_HOURS=24 +SQLALCHEMY_WARN_20=1 # Profiling system; uncomment to enable # Stores and exposes sensitive data! diff --git a/supervisord.conf.dev b/bootstrap/supervisord.conf.dev similarity index 100% rename from supervisord.conf.dev rename to bootstrap/supervisord.conf.dev diff --git a/supervisord.conf.release b/bootstrap/supervisord.conf.release similarity index 66% rename from supervisord.conf.release rename to bootstrap/supervisord.conf.release index 2ebb0138a..30d978f67 100644 --- a/supervisord.conf.release +++ b/bootstrap/supervisord.conf.release @@ -5,7 +5,7 @@ logfile=/tmp/supervisord.log [program:service] directory=/service -command=sh -c 'python3 -m flask db upgrade && ENABLE_SERVICES=true gunicorn files.__main__:app -k gevent -w $(( `nproc` * 2 )) --reload -b 0.0.0.0:80 --max-requests 1000 --max-requests-jitter 500' +command=sh -c 'python3 -m flask db upgrade && ENABLE_SERVICES=true gunicorn files.__main__:app -k gevent -w ${CORE_OVERRIDE:-$(( `nproc` * 2 ))} --reload -b 0.0.0.0:80 --max-requests 1000 --max-requests-jitter 500' stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 stderr_logfile=/dev/stderr diff --git a/docker-compose-operation.yml b/docker-compose-operation.yml index 02ddedfea..d274800ce 100644 --- a/docker-compose-operation.yml +++ b/docker-compose-operation.yml @@ -1,7 +1,6 @@ version: '2.3' services: - files: - container_name: "themotte" + site: build: target: operation diff --git a/docker-compose.yml b/docker-compose.yml index 39cfa2100..64388e811 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,14 +1,13 @@ version: '2.3' services: - files: - container_name: "themotte" + site: build: context: . target: dev volumes: - "./:/service" - env_file: env + env_file: bootstrap/site_env environment: - DATABASE_URL=postgresql://postgres@postgres:5432 - REDIS_URL=redis://redis @@ -23,19 +22,17 @@ services: - postgres redis: - container_name: "themotte_redis" image: redis ports: - "6379:6379" postgres: - container_name: "themotte_postgres" image: postgres:12.3 # command: ["postgres", "-c", "log_statement=all"] # uncomment this if u wanna output all SQL queries to the console volumes: - - "./schema.sql:/docker-entrypoint-initdb.d/00-schema.sql" - - "./seed-db.sql:/docker-entrypoint-initdb.d/10-seed-db.sql" + - "./bootstrap/original-schema.sql:/docker-entrypoint-initdb.d/00-schema.sql" + - "./bootstrap/original-seed-db.sql:/docker-entrypoint-initdb.d/10-seed-db.sql" environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: diff --git a/files/__main__.py b/files/__main__.py index 78351a36e..32a7c0ba2 100644 --- a/files/__main__.py +++ b/files/__main__.py @@ -141,8 +141,8 @@ app.config['RATE_LIMITER_ENABLED'] = not bool_from_string(environ.get('DBG_LIMIT if not app.config['RATE_LIMITER_ENABLED']: print("Rate limiter disabled in debug mode!") limiter = Limiter( - app, key_func=get_remote_addr, + app=app, default_limits=["3/second;30/minute;200/hour;1000/day"], application_limits=["10/second;200/minute;5000/hour;10000/day"], storage_uri=environ.get("REDIS_URL", "redis://localhost"), diff --git a/files/assets/js/bugs.js b/files/assets/js/bugs.js deleted file mode 100644 index 95d21d6e9..000000000 --- a/files/assets/js/bugs.js +++ /dev/null @@ -1,7 +0,0 @@ -new BugController({ - imageSprite: "/assets/images/fly-sprite.webp", - canDie: false, - minBugs: 10, - maxBugs: 20, - mouseOver: "multiply" -}); diff --git a/files/assets/js/critters.js b/files/assets/js/critters.js deleted file mode 100644 index c328faa56..000000000 --- a/files/assets/js/critters.js +++ /dev/null @@ -1,33 +0,0 @@ -var BugDispatch={options:{minDelay:500,maxDelay:1E4,minBugs:2,maxBugs:20,minSpeed:5,maxSpeed:10,maxLargeTurnDeg:150,maxSmallTurnDeg:10,maxWiggleDeg:5,imageSprite:"fireflies.webp",bugWidth:13,bugHeight:14,num_frames:5,zoom:10,canFly:!0,canDie:!0,numDeathTypes:3,monitorMouseMovement:!1,eventDistanceToBug:40,minTimeBetweenMultipy:1E3,mouseOver:"random"},initialize:function(a){this.options=mergeOptions(this.options,a);this.options.minBugs>this.options.maxBugs&&(this.options.minBugs=this.options.maxBugs); -this.modes=["multiply","nothing"];this.options.canFly&&this.modes.push("fly","flyoff");this.options.canDie&&this.modes.push("die");-1==this.modes.indexOf(this.options.mouseOver)&&(this.options.mouseOver="random");this.transform=null;this.transforms={Moz:function(a){this.bug.style.MozTransform=a},webkit:function(a){this.bug.style.webkitTransform=a},O:function(a){this.bug.style.OTransform=a},ms:function(a){this.bug.style.msTransform=a},Khtml:function(a){this.bug.style.KhtmlTransform=a},w3c:function(a){this.bug.style.transform= -a}};if("transform"in document.documentElement.style)this.transform=this.transforms.w3c;else{var b=["Moz","webkit","O","ms","Khtml"],c=0;for(c=0;cb?d=b:dc||(200=--this.toggle_stationary_counter&&this.toggleStationary(),this.stationary))){if(0>=--this.edge_test_counter&&this.bug_near_window_edge()&&(this.angle_deg%=360,0>this.angle_deg&&(this.angle_deg+=360),15=--this.large_turn_counter&&(this.large_turn_angle_deg=this.random(1,this.options.maxLargeTurnDeg,!0),this.next_large_turn());if(0>=--this.small_turn_counter)this.angle_deg+=this.random(1,this.options.maxSmallTurnDeg),this.next_small_turn();else{a=this.random(1,this.options.maxWiggleDeg,!0);if(0a||0>this.large_turn_angle_deg&&0=this.options.num_frames&&(this.walkIndex=0)},fly:function(a){var b=this.bug.top,c=this.bug.left,d=c-a.left,e=b-a.top,f=Math.atan(e/d);50>Math.abs(d)+Math.abs(e)&&(this.bug.style.backgroundPosition=-2*this.options.bugWidth+ -"px -"+2*this.options.bugHeight+"px");30>Math.abs(d)+Math.abs(e)&&(this.bug.style.backgroundPosition=-1*this.options.bugWidth+"px -"+2*this.options.bugHeight+"px");if(10>Math.abs(d)+Math.abs(e))this.bug.style.backgroundPosition="0 0",this.stop(),this.go();else{var g=Math.cos(f)*this.options.flySpeed;f=Math.sin(f)*this.options.flySpeed;if(c>a.left&&0a.left&&0>g)g*=-1,Math.abs(d)f||b>a.top&&0a&&(a=0);0===a?(a=-2*this.options.bugHeight,b*=Math.random()):1===a?(a=Math.random()*c,b+=2*this.options.bugWidth): -2===a?(a=c+2*this.options.bugHeight,b*=Math.random()):(a=Math.random()*c,b=-3*this.options.bugWidth);this.bug.style.backgroundPosition=-3*this.options.bugWidth+"px "+(this.wingsOpen?"0":"-"+this.options.bugHeight+"px");this.bug.top=a;this.bug.left=b;this.drawBug();a={};a.top=this.random(this.options.edge_resistance,document.documentElement.clientHeight-this.options.edge_resistance);a.left=this.random(this.options.edge_resistance,document.documentElement.clientWidth-this.options.edge_resistance);this.startFlying(a)}}, -walkIn:function(){this.bug||this.makeBug();if(this.bug){this.stop();var a=Math.round(4*Math.random()-.5),b=document,c=b.documentElement,d=b.getElementsByTagName("body")[0];b=window.innerWidth||c.clientWidth||d.clientWidth;c=window.innerHeight||c.clientHeight||d.clientHeight;3a&&(a=0);0===a?(a=-1.3*this.options.bugHeight,b*=Math.random()):1===a?(a=Math.random()*c,b+=.3*this.options.bugWidth):2===a?(a=c+.3*this.options.bugHeight,b*=Math.random()):(a=Math.random()*c,b=-1.3*this.options.bugWidth); -this.bug.style.backgroundPosition=-3*this.options.bugWidth+"px "+(this.wingsOpen?"0":"-"+this.options.bugHeight+"px");this.bug.top=a;this.bug.left=b;this.drawBug();this.go()}},flyOff:function(){this.stop();var a=this.random(0,3),b={},c=document,d=c.documentElement,e=c.getElementsByTagName("body")[0];c=window.innerWidth||d.clientWidth||e.clientWidth;d=window.innerHeight||d.clientHeight||e.clientHeight;0===a?(b.top=-200,b.left=Math.random()*c):1===a?(b.top=Math.random()*d,b.left=c+200):2===a?(b.top= -d+200,b.left=Math.random()*c):(b.top=Math.random()*d,b.left=-200);this.startFlying(b)},die:function(){this.stop();var a=this.random(0,this.options.numDeathTypes-1);this.alive=!1;this.drop(a)},drop:function(a){var b=this.bug.top,c=document,d=c.documentElement;c=c.getElementsByTagName("body")[0];var e=window.innerHeight||d.clientHeight||c.clientHeight;e-=this.options.bugHeight;var f=this.random(0,20,!0);Date.now();var g=this;this.bug.classList.add("bug-dead");this.dropTimer=requestAnimFrame(function(c){g._lastTimestamp= -c;g.dropping(c,b,e,f,a)})},dropping:function(a,b,c,d,e){a-=this._lastTimestamp;var f=b+.002*a*a,g=this;f>=c?(f=c,clearTimeout(this.dropTimer),this.angle_deg=0,this.angle_rad=this.deg2rad(this.angle_deg),this.transform("rotate("+(90-this.angle_deg)+"deg) scale("+this.zoom+")"),this.bug.style.top=null,this.bug.style.bottom=Math.ceil((this.options.bugWidth*this.zoom-this.options.bugHeight*this.zoom)/2-this.options.bugHeight/2*(1-this.zoom))+"px",this.bug.style.left=this.bug.left+"px",this.bug.style.backgroundPosition= -"-"+2*e*this.options.bugWidth+"px 100%",this.twitch(e)):(this.dropTimer=requestAnimFrame(function(a){g.dropping(a,b,c,d,e)}),20>a||(this.angle_deg=(this.angle_deg+d)%360,this.angle_rad=this.deg2rad(this.angle_deg),this.moveBug(this.bug.left,f,this.angle_deg)))},twitch:function(a,b){b||(b=0);var c=this;if(0===a||1===a)c.twitchTimer=setTimeout(function(){c.bug.style.backgroundPosition="-"+(2*a+b%2)*c.options.bugWidth+"px 100%";c.twitchTimer=setTimeout(function(){b++;c.bug.style.backgroundPosition="-"+ -(2*a+b%2)*c.options.bugWidth+"px 100%";c.twitch(a,++b)},c.random(300,800))},this.random(1E3,1E4))},rad2deg:function(a){return a*this.rad2deg_k},deg2rad:function(a){return a*this.deg2rad_k},random:function(a,b,c){if(a==b)return a;a=Math.round(a-.5+Math.random()*(b-a+1));return c?.5document.documentElement.clientHeight-this.options.edge_resistance&&(this.near_edge|=this.NEAR_BOTTOM_EDGE);this.bug.leftdocument.documentElement.clientWidth-this.options.edge_resistance&&(this.near_edge|=this.NEAR_RIGHT_EDGE);return this.near_edge},getPos:function(){return this.inserted&& -this.bug&&this.bug.style?{top:parseInt(this.bug.top,10),left:parseInt(this.bug.left,10)}:null}},SpawnBug=function(){var a={},b;for(b in Bug)Bug.hasOwnProperty(b)&&(a[b]=Bug[b]);return a},mergeOptions=function(a,b,c){"undefined"==typeof c&&(c=!0);a=c?cloneOf(a):a;for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);return a},cloneOf=function(a){if(null==a||"object"!=typeof a)return a;var b=a.constructor(),c;for(c in a)a.hasOwnProperty(c)&&(b[c]=cloneOf(a[c]));return b}; -window.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a,b){window.setTimeout(a,1E3/60)}}(); diff --git a/files/assets/js/fireflies.js b/files/assets/js/fireflies.js deleted file mode 100644 index 39ba5fbbd..000000000 --- a/files/assets/js/fireflies.js +++ /dev/null @@ -1,7 +0,0 @@ -new BugController({ - imageSprite: "/assets/images/fireflies.webp", - canDie: false, - minBugs: 10, - maxBugs: 30, - mouseOver: "multiply" -}); diff --git a/files/assets/js/userpage.js b/files/assets/js/userpage.js deleted file mode 100644 index 5d1845b8a..000000000 --- a/files/assets/js/userpage.js +++ /dev/null @@ -1,53 +0,0 @@ -let u_username = document.getElementById('u_username') - -if (u_username) -{ - u_username = u_username.innerHTML - - let audio = new Audio(`/@${u_username}/song`); - audio.loop=true; - - function toggle() { - if (audio.paused) audio.play() - else audio.pause() - } - - audio.play(); - document.getElementById('userpage').addEventListener('click', () => { - if (audio.paused) audio.play(); - }, {once : true}); -} -else -{ - let v_username = document.getElementById('v_username') - if (v_username) - { - v_username = v_username.innerHTML - - const paused = localStorage.getItem("paused") - - let audio = new Audio(`/@${v_username}/song`); - audio.loop=true; - - function toggle() { - if (audio.paused) - { - audio.play() - localStorage.setItem("paused", "") - } - else - { - audio.pause() - localStorage.setItem("paused", "1") - } - } - - if (!paused) - { - audio.play(); - window.addEventListener('click', () => { - if (audio.paused) audio.play(); - }, {once : true}); - } - } -} diff --git a/files/classes/__init__.py b/files/classes/__init__.py index c7284a035..e121825a5 100644 --- a/files/classes/__init__.py +++ b/files/classes/__init__.py @@ -82,7 +82,7 @@ from .volunteer_janitor import VolunteerJanitorRecord # Then the import * from files.* from files.helpers.const import * -from files.helpers.images import * +from files.helpers.media import * from files.helpers.lazy import * from files.helpers.security import * diff --git a/files/classes/clients.py b/files/classes/clients.py index ebb1d2670..731c4b785 100644 --- a/files/classes/clients.py +++ b/files/classes/clients.py @@ -16,7 +16,7 @@ class OauthApp(Base): ) id = Column(Integer, primary_key=True) - client_id = Column(String) + client_id = Column(String(length=64)) app_name = Column(String(length=50), nullable=False) redirect_uri = Column(String(length=50), nullable=False) description = Column(String(length=256), nullable=False) @@ -35,7 +35,7 @@ class OauthApp(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @property @lazy @@ -74,7 +74,7 @@ class ClientAuth(Base): user_id = Column(Integer, ForeignKey("users.id"), primary_key=True) oauth_client = Column(Integer, ForeignKey("oauth_apps.id"), primary_key=True) - access_token = Column(String, nullable=False) + access_token = Column(String(128), nullable=False) user = relationship("User", viewonly=True) application = relationship("OauthApp", viewonly=True) @@ -87,4 +87,4 @@ class ClientAuth(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) diff --git a/files/classes/comment.py b/files/classes/comment.py index 65360f512..fa2ae8f9e 100644 --- a/files/classes/comment.py +++ b/files/classes/comment.py @@ -109,7 +109,7 @@ class Comment(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @property @lazy @@ -194,12 +194,9 @@ class Comment(Base): @property @lazy def parent(self): - if not self.parent_submission: return None - if self.level == 1: return self.post - - else: return g.db.query(Comment).get(self.parent_comment_id) + else: return g.db.get(Comment, self.parent_comment_id) @property @lazy @@ -295,13 +292,14 @@ class Comment(Base): return data def award_count(self, kind): + if not FEATURES['AWARDS']: return 0 return len([x for x in self.awards if x.kind == kind]) @property @lazy def json_core(self): if self.is_banned: - data= {'is_banned': True, + data = {'is_banned': True, 'ban_reason': self.ban_reason, 'id': self.id, 'post': self.post.id if self.post else 0, @@ -309,38 +307,27 @@ class Comment(Base): 'parent': self.parent_fullname } elif self.deleted_utc: - data= {'deleted_utc': self.deleted_utc, + data = {'deleted_utc': self.deleted_utc, 'id': self.id, 'post': self.post.id if self.post else 0, 'level': self.level, 'parent': self.parent_fullname } else: + data = self.json_raw + if self.level >= 2: data['parent_comment_id']= self.parent_comment_id - data=self.json_raw - - if self.level>=2: data['parent_comment_id']= self.parent_comment_id - - data['replies']=[x.json_core for x in self.replies(None)] + data['replies'] = [x.json_core for x in self.replies(None)] return data @property @lazy def json(self): - - data=self.json_core - - if self.deleted_utc or self.is_banned: - return data - - data["author"]='👻' if self.ghost else self.author.json_core - data["post"]=self.post.json_core if self.post else '' - - if self.level >= 2: - data["parent"]=self.parent.json_core - - + data = self.json_core + if self.deleted_utc or self.is_banned: return data + data["author"] = '👻' if self.ghost else self.author.json_core + data["post"] = self.post.json_core if self.post else '' return data def realbody(self, v): @@ -385,17 +372,10 @@ class Comment(Base): def plainbody(self, v): if self.post and self.post.club and not (v and (v.paid_dues or v.id in [self.author_id, self.post.author_id])): return f"

{CC} ONLY

" - body = self.body - if not body: return "" - return body - def print(self): - print(f'post: {self.id}, comment: {self.author_id}', flush=True) - return '' - @lazy def collapse_for_user(self, v, path): if v and self.author_id == v.id: return False diff --git a/files/classes/flags.py b/files/classes/flags.py index add15325e..56030ff68 100644 --- a/files/classes/flags.py +++ b/files/classes/flags.py @@ -34,7 +34,7 @@ class Flag(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @lazy def realreason(self, v): @@ -70,7 +70,7 @@ class CommentFlag(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @lazy def realreason(self, v): diff --git a/files/classes/leaderboard.py b/files/classes/leaderboard.py new file mode 100644 index 000000000..4697d39bf --- /dev/null +++ b/files/classes/leaderboard.py @@ -0,0 +1,252 @@ +from dataclasses import dataclass +from typing import Any, Callable, Final, Optional + +from sqlalchemy import Column, func +from sqlalchemy.orm import scoped_session, Query + +from files.helpers.const import LEADERBOARD_LIMIT + +from files.classes.badges import Badge +from files.classes.marsey import Marsey +from files.classes.user import User +from files.classes.userblock import UserBlock +from files.helpers.get import get_accounts_dict + +@dataclass(frozen=True, slots=True) +class LeaderboardMeta: + header_name:str + table_header_name:str + html_id:str + table_column_name:str + user_relative_url:Optional[str] + limit:int=LEADERBOARD_LIMIT + +class Leaderboard: + def __init__(self, v:Optional[User], meta:LeaderboardMeta) -> None: + self.v:Optional[User] = v + self.meta:LeaderboardMeta = meta + + @property + def all_users(self) -> list[User]: + raise NotImplementedError() + + @property + def v_position(self) -> Optional[int]: + raise NotImplementedError() + + @property + def v_value(self) -> Optional[int]: + raise NotImplementedError() + + @property + def v_appears_in_ranking(self) -> bool: + return self.v_position is not None and self.v_position <= len(self.all_users) + + @property + def user_func(self) -> Callable[[Any], User]: + return lambda u:u + + @property + def value_func(self) -> Callable[[User], int]: + raise NotImplementedError() + +class SimpleLeaderboard(Leaderboard): + def __init__(self, v:User, meta:LeaderboardMeta, db:scoped_session, users_query:Query, column:Column): + super().__init__(v, meta) + self.db:scoped_session = db + self.users_query:Query = users_query + self.column:Column = column + self._calculate() + + def _calculate(self) -> None: + self._all_users = self.users_query.order_by(self.column.desc()).limit(self.meta.limit).all() + if self.v not in self._all_users: + sq = self.db.query(User.id, self.column, func.rank().over(order_by=self.column.desc()).label("rank")).subquery() + sq_data = self.db.query(sq.c.id, sq.c.column, sq.c.rank).filter(sq.c.id == self.v.id).limit(1).one() + self._v_value:int = sq_data[1] + self._v_position:int = sq_data[2] + + @property + def all_users(self) -> list[User]: + return self._all_users + + @property + def v_position(self) -> int: + return self._v_position + + @property + def v_value(self) -> int: + return self._v_value + + @property + def value_func(self) -> Callable[[User], int]: + return lambda u:getattr(u, self.column.name) + +class _CountedAndRankedLeaderboard(Leaderboard): + @classmethod + def count_and_label(cls, criteria): + return func.count(criteria).label("count") + + @classmethod + def rank_filtered_rank_label_by_desc(cls, criteria): + return func.rank().over(order_by=func.count(criteria).desc()).label("rank") + +class BadgeMarseyLeaderboard(_CountedAndRankedLeaderboard): + def __init__(self, v:User, meta:LeaderboardMeta, db:scoped_session, column:Column): + super().__init__(v, meta) + self.db:scoped_session = db + self.column = column + self._calculate() + + def _calculate(self): + sq = self.db.query(self.column, self.count_and_label(self.column), self.rank_filtered_rank_label_by_desc(self.column)).group_by(self.column).subquery() + sq_criteria = None + if self.column == Badge.user_id: + sq_criteria = User.id == sq.c.user_id + elif self.column == Marsey.author_id: + sq_criteria = User.id == sq.c.author_id + else: + raise ValueError("This leaderboard function only supports Badge.user_id and Marsey.author_id") + leaderboard = self.db.query(User, sq.c.count).join(sq, sq_criteria).order_by(sq.c.count.desc()) + + position:Optional[tuple[int, int, int]] = self.db.query(User.id, sq.c.rank, sq.c.count).join(sq, sq_criteria).filter(User.id == self.v.id).one_or_none() + if position and position[1]: + self._v_position = position[1] + self._v_value = position[2] + else: + self._v_position = leaderboard.count() + 1 + self._v_value = 0 + self._all_users = {k:v for k, v in leaderboard.limit(self.meta.limit).all()} + + @property + def all_users(self) -> list[User]: + return list(self._all_users.keys()) + + @property + def v_position(self) -> int: + return self._v_position + + @property + def v_value(self) -> int: + return self._v_value + + @property + def value_func(self) -> Callable[[User], int]: + return lambda u:self._all_users[u] + +class UserBlockLeaderboard(_CountedAndRankedLeaderboard): + def __init__(self, v:User, meta:LeaderboardMeta, db:scoped_session, column:Column): + super().__init__(v, meta) + self.db:scoped_session = db + self.column = column + self._calculate() + + def _calculate(self): + if self.column != UserBlock.target_id: + raise ValueError("This leaderboard function only supports UserBlock.target_id") + sq = self.db.query(self.column, self.count_and_label(self.column)).group_by(self.column).subquery() + leaderboard = self.db.query(User, sq.c.count).join(User, User.id == sq.c.target_id).order_by(sq.c.count.desc()) + + sq = self.db.query(self.column, self.count_and_label(self.column), self.rank_filtered_rank_label_by_desc(self.column)).group_by(self.column).subquery() + position = self.db.query(sq.c.rank, sq.c.count).join(User, User.id == sq.c.target_id).filter(sq.c.target_id == self.v.id).limit(1).one_or_none() + if not position: position = (leaderboard.count() + 1, 0) + leaderboard = leaderboard.limit(self.meta.limit).all() + self._all_users = {k:v for k, v in leaderboard} + self._v_position = position[0] + self._v_value = position[1] + return (leaderboard, position[0], position[1]) + + @property + def all_users(self) -> list[User]: + return list(self._all_users.keys()) + + @property + def v_position(self) -> int: + return self._v_position + + @property + def v_value(self) -> int: + return self._v_value + +class RawSqlLeaderboard(Leaderboard): + def __init__(self, meta:LeaderboardMeta, db:scoped_session, query:str) -> None: # should be LiteralString on py3.11+ + super().__init__(None, meta) + self.db = db + self._calculate(query) + + def _calculate(self, query:str): + self.result = {result[0]:list(result) for result in self.db.execute(query).all()} + users = get_accounts_dict(self.result.keys(), db=self.db) + if users is None: + raise Exception("Some users don't exist when they should (was a user deleted?)") + for user in users: # I know. + self.result[user].append(users[user]) + + @property + def all_users(self) -> list[User]: + return [result[2] for result in self.result.values()] + + @property + def v_position(self) -> Optional[int]: + return None + + @property + def v_value(self) -> Optional[int]: + return None + + @property + def v_appears_in_ranking(self) -> bool: + return True # we set this to True here to try and not grab the data + + @property + def user_func(self) -> Callable[[Any], User]: + return lambda u:u + + @property + def value_func(self) -> Callable[[User], int]: + return lambda u:self.result[u.id][1] + +class ReceivedDownvotesLeaderboard(RawSqlLeaderboard): + _query: Final[str] = """ + WITH cv_for_user AS ( + SELECT + comments.author_id AS target_id, + COUNT(*) + FROM commentvotes cv + JOIN comments ON comments.id = cv.comment_id + WHERE vote_type = -1 + GROUP BY comments.author_id +), sv_for_user AS ( + SELECT + submissions.author_id AS target_id, + COUNT(*) + FROM votes sv + JOIN submissions ON submissions.id = sv.submission_id + WHERE vote_type = -1 + GROUP BY submissions.author_id +) +SELECT + COALESCE(cvfu.target_id, svfu.target_id) AS target_id, + (COALESCE(cvfu.count, 0) + COALESCE(svfu.count, 0)) AS count +FROM cv_for_user cvfu + FULL OUTER JOIN sv_for_user svfu + ON cvfu.target_id = svfu.target_id +ORDER BY count DESC LIMIT 25 + """ + + def __init__(self, meta:LeaderboardMeta, db:scoped_session) -> None: + super().__init__(meta, db, self._query) + +class GivenUpvotesLeaderboard(RawSqlLeaderboard): + _query: Final[str] = """ + SELECT + COALESCE(cvbu.user_id, svbu.user_id) AS user_id, + (COALESCE(cvbu.count, 0) + COALESCE(svbu.count, 0)) AS count +FROM (SELECT user_id, COUNT(*) FROM votes WHERE vote_type = 1 GROUP BY user_id) AS svbu +FULL OUTER JOIN (SELECT user_id, COUNT(*) FROM commentvotes WHERE vote_type = 1 GROUP BY user_id) AS cvbu + ON cvbu.user_id = svbu.user_id +ORDER BY count DESC LIMIT 25 + """ + + def __init__(self, meta:LeaderboardMeta, db:scoped_session) -> None: + super().__init__(meta, db, self._query) diff --git a/files/classes/submission.py b/files/classes/submission.py index 0640de4be..5ce10e92d 100644 --- a/files/classes/submission.py +++ b/files/classes/submission.py @@ -106,12 +106,12 @@ class Submission(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @property @lazy @@ -178,7 +178,7 @@ class Submission(Base): @property @lazy def edited_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.edited_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.edited_utc)) @property @@ -331,6 +331,7 @@ class Submission(Base): return data def award_count(self, kind): + if not FEATURES['AWARDS']: return 0 return len([x for x in self.awards if x.kind == kind]) @lazy @@ -340,8 +341,8 @@ class Submission(Base): url = self.url.replace("old.reddit.com", v.reddit) if '/comments/' in url and "sort=" not in url: - if "?" in url: url += "&context=9" - else: url += "?context=8" + if "?" in url: url += f"&context={RENDER_DEPTH_LIMIT}" + else: url += f"?context={RENDER_DEPTH_LIMIT - 1}" if v.controversial: url += "&sort=controversial" return url elif self.url: @@ -376,22 +377,13 @@ class Submission(Base): def plainbody(self, v): if self.club and not (v and (v.paid_dues or v.id == self.author_id)): return f"

{CC} ONLY

" - body = self.body - if not body: return "" - if v: body = body.replace("old.reddit.com", v.reddit) - if v.nitter and '/i/' not in body and '/retweets' not in body: body = body.replace("www.twitter.com", "nitter.net").replace("twitter.com", "nitter.net") - return body - def print(self): - print(f'post: {self.id}, author: {self.author_id}', flush=True) - return '' - @lazy def realtitle(self, v): if self.title_html: diff --git a/files/classes/user.py b/files/classes/user.py index 95d85c50e..f108d86a0 100644 --- a/files/classes/user.py +++ b/files/classes/user.py @@ -1,7 +1,7 @@ from sqlalchemy.orm import deferred, aliased from secrets import token_hex import pyotp -from files.helpers.images import * +from files.helpers.media import * from files.helpers.const import * from .alts import Alt from .saves import * @@ -44,7 +44,6 @@ class User(Base): theme = Column(String, default=defaulttheme, nullable=False) themecolor = Column(String, default=DEFAULT_COLOR, nullable=False) cardview = Column(Boolean, default=cardview, nullable=False) - song = Column(String) highres = Column(String) profileurl = Column(String) bannerurl = Column(String) @@ -196,13 +195,10 @@ class User(Base): @property @lazy def user_awards(self): - - return_value = list(AWARDS2.values()) - + if not FEATURES['AWARDS']: return [] + return_value = list(AWARDS_ENABLED.values()) user_awards = g.db.query(AwardRelationship).filter_by(user_id=self.id) - for val in return_value: val['owned'] = user_awards.filter_by(kind=val['kind'], submission_id=None, comment_id=None).count() - return return_value @property @@ -352,7 +348,7 @@ class User(Base): @property @lazy def received_awards(self): - + if not FEATURES['AWARDS']: return [] awards = {} posts_idlist = [x[0] for x in g.db.query(Submission.id).filter_by(author_id=self.id).all()] @@ -563,7 +559,7 @@ class User(Base): @property @lazy def created_datetime(self): - return str(time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc))) + return time.strftime("%d/%B/%Y %H:%M:%S UTC", time.gmtime(self.created_utc)) @lazy def subscribed_idlist(self, page=1): @@ -620,3 +616,9 @@ class User(Base): l = [i.strip() for i in self.custom_filter_list.split('\n')] if self.custom_filter_list else [] l = [i for i in l if i] return l + + # Permissions + + @property + def can_see_shadowbanned(self): + return self.admin_level >= PERMS['USER_SHADOWBAN'] or self.shadowbanned diff --git a/files/commands/seed_db.py b/files/commands/seed_db.py index 52813d07d..5c462cb82 100644 --- a/files/commands/seed_db.py +++ b/files/commands/seed_db.py @@ -1,38 +1,41 @@ import hashlib import math +from typing import Optional import sqlalchemy -from werkzeug.security import generate_password_hash -from files.__main__ import app -from files.classes import User, Submission, Comment, Vote, CommentVote -from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.orm import scoped_session -db = SQLAlchemy(app) +from werkzeug.security import generate_password_hash + +from files.__main__ import app, db_session +from files.classes import User, Submission, Comment, Vote, CommentVote +from files.helpers.comments import bulk_recompute_descendant_counts @app.cli.command('seed_db') def seed_db(): + seed_db_worker() + +def seed_db_worker(num_users = 900, num_posts = 40, num_toplevel_comments = 1000, num_reply_comments = 400): """ Seed the database with some example data. """ - NUM_USERS = 900; - NUM_POSTS = 40; - NUM_TOPLEVEL_COMMENTS = 1000 - NUM_REPLY_COMMENTS = 4000 POST_UPVOTE_PROB = 0.020 POST_DOWNVOTE_PROB = 0.005 COMMENT_UPVOTE_PROB = 0.0008 COMMENT_DOWNVOTE_PROB = 0.0003 + db: scoped_session = db_session() + def detrand(): detrand.randstate = bytes(hashlib.sha256(detrand.randstate).hexdigest(), 'utf-8') return int(detrand.randstate, 16) / 2**256 detrand.randstate = bytes(hashlib.sha256(b'init').hexdigest(), 'utf-8') - users = db.session.query(User).where(User.id >= 10).all() - posts = db.session.query(Submission).all() - comments = db.session.query(Comment).all() + users = db.query(User).where(User.id >= 10).all() + posts = db.query(Submission).all() + comments = db.query(Comment).all() - admin = db.session.query(User).filter(User.id == 9).first() + admin = db.query(User).filter(User.id == 9).first() if admin is None: admin = User(**{ "username": "admin", @@ -43,7 +46,7 @@ def seed_db(): "ban_evade":0, "profileurl":"/e/feather.webp" }) - db.session.add(admin) + db.add(admin) class UserWithFastPasswordHash(User): def hash_password(self, password): @@ -55,10 +58,10 @@ def seed_db(): salt_length=8 ) - print(f"Creating {NUM_USERS} users") - users_by_id = {user_id: None for user_id in range(10, 10 + NUM_USERS)} + print(f"Creating {num_users} users") + users_by_id: dict[int, Optional[User]] = {user_id: None for user_id in range(10, 10 + num_users)} for user_id, user in users_by_id.items(): - user = db.session.query(User).filter(User.id == user_id).first() + user = db.query(User).filter(User.id == user_id).first() if user is None: user = UserWithFastPasswordHash(**{ "username": f"user{user_id:03d}", @@ -69,22 +72,22 @@ def seed_db(): "ban_evade":0, "profileurl":"/e/feather.webp" }) - db.session.add(user) + db.add(user) users_by_id[user_id] = user - db.session.commit() - db.session.flush() + db.commit() + db.flush() users = list(users_by_id.values()) - db.session.commit() - db.session.flush() + db.commit() + db.flush() posts = [] - print(f"Creating {NUM_POSTS} posts") + print(f"Creating {num_posts} posts") # 40 top-level posts - for i in range(NUM_POSTS): + for i in range(num_posts): user = users[int(len(users) * detrand())] post = Submission( private=False, @@ -102,16 +105,15 @@ def seed_db(): ghost=False, filter_state='normal' ) - db.session.add(post) + db.add(post) posts.append(post) - db.session.commit() - db.session.flush() + db.commit() - print(f"Creating {NUM_TOPLEVEL_COMMENTS} top-level comments") + print(f"Creating {num_toplevel_comments} top-level comments") comments = [] # 2k top-level comments, distributed by power-law - for i in range(NUM_TOPLEVEL_COMMENTS): + for i in range(num_toplevel_comments): user = users[int(len(users) * detrand())] parent = posts[int(-math.log(detrand()) / math.log(1.4))] comment = Comment( @@ -126,22 +128,22 @@ def seed_db(): body=f'toplevel {i}', ghost=False ) - db.session.add(comment) + db.add(comment) comments.append(comment) - db.session.flush() + db.flush() for c in comments: c.top_comment_id = c.id - db.session.add(c) + db.add(c) - db.session.commit() + db.commit() - print(f"Creating {NUM_REPLY_COMMENTS} reply comments") - for i in range(NUM_REPLY_COMMENTS): + print(f"Creating {num_reply_comments} reply comments") + for i in range(num_reply_comments): user = users[int(len(users) * detrand())] parent = comments[int(len(comments) * detrand())] if parent.id is None: - db.session.commit() + db.commit() comment = Comment( author_id=user.id, parent_submission=str(parent.post.id), @@ -155,18 +157,18 @@ def seed_db(): body=f'reply {i}', ghost=False ) - db.session.add(comment) + db.add(comment) comments.append(comment) - db.session.commit() + db.commit() print("Updating comment counts for all posts") for post in posts: post.comment_count = len(post.comments) - db.session.merge(post) + db.merge(post) print("Adding upvotes and downvotes to posts") - postvotes = db.session.query(Vote).all() + postvotes = db.query(Vote).all() postvotes_pk_set = set((v.submission_id, v.user_id) for v in postvotes) for user in users: @@ -189,10 +191,10 @@ def seed_db(): app_id=None, real=True ) - db.session.add(vote) + db.add(vote) print("Adding upvotes and downvotes to comments") - commentvotes = db.session.query(CommentVote).all() + commentvotes = db.query(CommentVote).all() commentvotes_pk_set = set((v.comment_id, v.user_id) for v in commentvotes) for user in users: @@ -215,34 +217,33 @@ def seed_db(): app_id=None, real=True ) - db.session.add(vote) + db.add(vote) - db.session.commit() - db.session.flush() + db.commit() post_upvote_counts = dict( - db.session + db .query(Vote.submission_id, sqlalchemy.func.count(1)) .filter(Vote.vote_type == +1) .group_by(Vote.submission_id) .all() ) post_downvote_counts = dict( - db.session + db .query(Vote.submission_id, sqlalchemy.func.count(1)) .filter(Vote.vote_type == -1) .group_by(Vote.submission_id) .all() ) comment_upvote_counts = dict( - db.session + db .query(CommentVote.comment_id, sqlalchemy.func.count(1)) .filter(CommentVote.vote_type == +1) .group_by(CommentVote.comment_id) .all() ) comment_downvote_counts = dict( - db.session + db .query(CommentVote.comment_id, sqlalchemy.func.count(1)) .filter(CommentVote.vote_type == -1) .group_by(CommentVote.comment_id) @@ -253,13 +254,15 @@ def seed_db(): post.upvotes = post_upvote_counts.get(post.id, 0) post.downvotes = post_downvote_counts.get(post.id, 0) post.realupvotes = post.upvotes - post.downvotes - db.session.add(post) + db.add(post) for comment in comments: comment.upvotes = comment_upvote_counts.get(comment.id, 0) comment.downvotes = comment_downvote_counts.get(comment.id, 0) comment.realupvotes = comment.upvotes - comment.downvotes - db.session.add(comment) + db.add(comment) - db.session.commit() - db.session.flush() + print("Computing comment descendant_count") + bulk_recompute_descendant_counts(db=db) + + db.commit() diff --git a/files/helpers/captcha.py b/files/helpers/captcha.py new file mode 100644 index 000000000..c80342fb3 --- /dev/null +++ b/files/helpers/captcha.py @@ -0,0 +1,14 @@ +from typing import Final +import requests + +HCAPTCHA_URL: Final[str] = "https://hcaptcha.com/siteverify" + +def validate_captcha(secret:str, sitekey: str, token: str): + if not sitekey: return True + if not token: return False + data = {"secret": secret, + "response": token, + "sitekey": sitekey + } + req = requests.post(HCAPTCHA_URL, data=data, timeout=5) + return bool(req.json()["success"]) diff --git a/files/helpers/comments.py b/files/helpers/comments.py index 4be95eced..5e04a336e 100644 --- a/files/helpers/comments.py +++ b/files/helpers/comments.py @@ -1,15 +1,15 @@ from pusher_push_notifications import PushNotifications -from files.classes import Comment, Notification, Subscription +from files.classes import Comment, Notification, Subscription, User from files.helpers.alerts import NOTIFY_USERS from files.helpers.const import PUSHER_ID, PUSHER_KEY, SITE_ID, SITE_FULL from files.helpers.assetcache import assetcache_path from flask import g from sqlalchemy import select, update from sqlalchemy.sql.expression import func, text, alias -from sqlalchemy.orm import aliased +from sqlalchemy.orm import Query, aliased from sys import stdout import gevent -import typing +from typing import Optional if PUSHER_ID != 'blahblahblah': beams_client = PushNotifications(instance_id=PUSHER_ID, secret_key=PUSHER_KEY) @@ -141,13 +141,13 @@ def bulk_recompute_descendant_counts(predicate = None, db=None): True ) .group_by(parent_comments.corresponding_column(Comment.id)) - .with_only_columns([ + .with_only_columns( parent_comments.corresponding_column(Comment.id), func.coalesce( func.sum(child_comments.corresponding_column(Comment.descendant_count) + text(str(1))), text(str(0)) ).label('descendant_count') - ]) + ) .subquery(name='descendant_counts') ), adapt_on_names=True @@ -217,3 +217,16 @@ def comment_on_unpublish(comment:Comment): reflect the comments users will actually see. """ update_stateful_counters(comment, -1) + + +def comment_filter_moderated(q: Query, v: Optional[User]) -> Query: + if not (v and v.shadowbanned) and not (v and v.admin_level > 2): + q = q.join(User, User.id == Comment.author_id) \ + .filter(User.shadowbanned == None) + if not v or v.admin_level < 2: + q = q.filter( + ((Comment.filter_state != 'filtered') + & (Comment.filter_state != 'removed')) + | (Comment.author_id == ((v and v.id) or 0)) + ) + return q diff --git a/files/helpers/const.py b/files/helpers/const.py index 224b6bdd4..6fa93fe3f 100644 --- a/files/helpers/const.py +++ b/files/helpers/const.py @@ -1,10 +1,12 @@ -from os import environ, listdir import re from copy import deepcopy -from json import loads +from os import environ +from typing import Final + +from flask import request + from files.__main__ import db_session from files.classes.marsey import Marsey -from flask import request SITE = environ.get("DOMAIN", '').strip() SITE_ID = environ.get("SITE_ID", '').strip() @@ -17,6 +19,7 @@ CC_TITLE = CC.title() NOTIFICATIONS_ID = 1 AUTOJANNY_ID = 2 +MODMAIL_ID = 2 SNAPPY_ID = 3 LONGPOSTBOT_ID = 4 ZOZBOT_ID = 5 @@ -31,10 +34,25 @@ BUG_THREAD = 0 WELCOME_MSG = f"Welcome to {SITE_TITLE}! Please read [the rules](/rules) first. Then [read some of our current conversations](/) and feel free to comment or post!\n\nWe encourage people to comment even if they aren't sure they fit in; as long as your comment follows [community rules](/rules), we are happy to have posters from all backgrounds, education levels, and specialties." ROLES={} +LEADERBOARD_LIMIT: Final[int] = 25 + THEMES = {"TheMotte", "dramblr", "reddit", "transparent", "win98", "dark", "light", "coffee", "tron", "4chan", "midnight"} +SORTS_COMMON = { + "top": 'fa-arrow-alt-circle-up', + "bottom": 'fa-arrow-alt-circle-down', + "new": 'fa-sparkles', + "old": 'fa-book', + "controversial": 'fa-bullhorn', + "comments": 'fa-comments' +} +SORTS_POSTS = { + "hot": "fa-fire", + "bump": "fa-arrow-up" +} +SORTS_POSTS.update(SORTS_COMMON) +SORTS_COMMENTS = SORTS_COMMON -IMGUR_KEY = environ.get("IMGUR_KEY").strip() PUSHER_ID = environ.get("PUSHER_ID", "").strip() PUSHER_KEY = environ.get("PUSHER_KEY", "").strip() DEFAULT_COLOR = environ.get("DEFAULT_COLOR", "fff").strip() @@ -54,6 +72,10 @@ ERROR_MESSAGES = { } LOGGEDIN_ACTIVE_TIME = 15 * 60 +RENDER_DEPTH_LIMIT = 9 +''' +The maximum depth at which a comment tree is rendered +''' WERKZEUG_ERROR_DESCRIPTIONS = { 400: "The browser (or proxy) sent a request that this server could not understand.", @@ -74,125 +96,29 @@ VIDEO_FORMATS = ['mp4','webm','mov','avi','mkv','flv','m4v','3gp'] AUDIO_FORMATS = ['mp3','wav','ogg','aac','m4a','flac'] NO_TITLE_EXTENSIONS = IMAGE_FORMATS + VIDEO_FORMATS + AUDIO_FORMATS +FEATURES = { + "AWARDS": False, +} + PERMS = { "DEBUG_LOGIN_TO_OTHERS": 3, + "USER_SHADOWBAN": 2, } -AWARDS = { - "lootbox": { - "kind": "lootbox", - "title": "Lootstocking", - "description": "???", - "icon": "fas fa-stocking", - "color": "text-danger", - "price": 1000 - }, - "shit": { - "kind": "shit", - "title": "Shit", - "description": "Makes flies swarm the post.", - "icon": "fas fa-poop", - "color": "text-black-50", - "price": 300 - }, - "fireflies": { - "kind": "fireflies", - "title": "Fireflies", - "description": "Makes fireflies swarm the post.", - "icon": "fas fa-sparkles", - "color": "text-warning", - "price": 300 - }, - "train": { - "kind": "train", - "title": "Train", - "description": "Summons a train on the post.", - "icon": "fas fa-train", - "color": "text-pink", - "price": 300 - }, - "scooter": { - "kind": "scooter", - "title": "Scooter", - "description": "Summons a scooter on the post.", - "icon": "fas fa-flag-usa", - "color": "text-muted", - "price": 300 - }, - "wholesome": { - "kind": "wholesome", - "title": "Wholesome", - "description": "Summons a wholesome marsey on the post.", - "icon": "fas fa-smile-beam", - "color": "text-yellow", - "price": 300 - }, - "glowie": { - "kind": "glowie", - "title": "Glowie", - "description": "Indicates that the recipient can be seen when driving. Just run them over.", - "icon": "fas fa-user-secret", - "color": "text-green", - "price": 300 - }, - "pin": { - "kind": "pin", - "title": "1-Hour Pin", - "description": "Pins the post/comment.", - "icon": "fas fa-thumbtack fa-rotate--45", - "color": "text-warning", - "price": 1000 - }, - "unpin": { - "kind": "unpin", - "title": "1-Hour Unpin", - "description": "Removes 1 hour from the pin duration of the post/comment.", - "icon": "fas fa-thumbtack fa-rotate--45", - "color": "text-black", - "price": 1000 - }, - "ban": { - "kind": "ban", - "title": "1-Day Ban", - "description": "Bans the recipient for a day.", - "icon": "fas fa-gavel", - "color": "text-danger", - "price": 3000 - }, - "unban": { - "kind": "unban", - "title": "1-Day Unban", - "description": "Removes 1 day from the ban duration of the recipient.", - "icon": "fas fa-gavel", - "color": "text-success", - "price": 3500 - }, - "benefactor": { - "kind": "benefactor", - "title": "Benefactor", - "description": "Grants one month of paypig status and 2500 marseybux to the recipient. Cannot be used on yourself.", - "icon": "fas fa-gift", - "color": "text-blue", - "price": 4000 - }, - "grass": { - "kind": "grass", - "title": "Grass", - "description": "Doesn't do anything", - "icon": "fas fa-seedling", - "color": "text-success", - "price": 10000 - }, -} +AWARDS = {} -AWARDS2 = deepcopy(AWARDS) -for k, val in AWARDS.items(): - if val['description'] == '???': AWARDS2.pop(k) +if FEATURES['AWARDS']: + AWARDS_ENABLED = deepcopy(AWARDS) + for k, val in AWARDS.items(): + if val['description'] == '???': AWARDS_ENABLED.pop(k) + AWARDS_JL2_PRINTABLE = {} + for k, val in AWARDS_ENABLED.items(): + if val['price'] == 300: AWARDS_JL2_PRINTABLE[k] = val +else: + AWARDS_ENABLED = {} + AWARDS_JL2_PRINTABLE = {} -AWARDS3 = {} -for k, val in AWARDS2.items(): - if val['price'] == 300: AWARDS3[k] = val NOTIFIED_USERS = { # format: 'substring' ↦ User ID to notify diff --git a/files/helpers/contentsorting.py b/files/helpers/contentsorting.py index bdb4fb1db..4d60d2fa5 100644 --- a/files/helpers/contentsorting.py +++ b/files/helpers/contentsorting.py @@ -1,9 +1,17 @@ import time +from collections.abc import Iterable +from typing import Any, TYPE_CHECKING from sqlalchemy.sql import func +from sqlalchemy.orm import Query from files.helpers.const import * +if TYPE_CHECKING: + from files.classes.comment import Comment +else: + Comment = Any + def apply_time_filter(objects, t, cls): now = int(time.time()) @@ -22,66 +30,75 @@ def apply_time_filter(objects, t, cls): return objects.filter(cls.created_utc >= cutoff) -def sort_objects(objects, sort, cls): +def sort_objects(objects: Query, sort: str, cls): if sort == 'hot': ti = int(time.time()) + 3600 - return objects.order_by( + ordered = objects.order_by( -100000 * (cls.upvotes + 1) - / (func.power((ti - cls.created_utc) / 1000, 1.23)), - cls.created_utc.desc()) + / (func.power((ti - cls.created_utc) / 1000, 1.23))) elif sort == 'bump' and cls.__name__ == 'Submission': - return objects.filter(cls.comment_count > 1).order_by( - cls.bump_utc.desc(), cls.created_utc.desc()) - elif sort == 'comments' and cls.__name__ == 'Submission': - return objects.order_by( - cls.comment_count.desc(), cls.created_utc.desc()) + ordered = objects.filter(cls.comment_count > 1).order_by(cls.bump_utc.desc()) + elif sort == 'comments': + if cls.__name__ == 'Submission': # we're checking the stringified name due to a gnarly import cycle + ordered = objects.order_by(cls.comment_count.desc()) + elif cls.__name__ == 'Comment': + ordered = objects.order_by(cls.descendant_count.desc()) + else: + ordered = objects elif sort == 'controversial': - return objects.order_by( + ordered = objects.order_by( (cls.upvotes + 1) / (cls.downvotes + 1) + (cls.downvotes + 1) / (cls.upvotes + 1), - cls.downvotes.desc(), cls.created_utc.desc()) + cls.downvotes.desc()) elif sort == 'top': - return objects.order_by( - cls.downvotes - cls.upvotes, cls.created_utc.desc()) + ordered = objects.order_by(cls.downvotes - cls.upvotes) elif sort == 'bottom': - return objects.order_by( - cls.upvotes - cls.downvotes, cls.created_utc.desc()) + ordered = objects.order_by(cls.upvotes - cls.downvotes) elif sort == 'old': return objects.order_by(cls.created_utc) else: # default, or sort == 'new' - return objects.order_by(cls.created_utc.desc()) + ordered = objects + ordered = ordered.order_by(cls.created_utc.desc()) + return ordered # Presently designed around files.helpers.get.get_comment_trees_eager # Behavior should parallel that of sort_objects above. TODO: Unify someday? -def sort_comment_results(comments, sort): - DESC = (2 << 30) - 1 # descending sorts, Y2038 problem, change before then +def sort_comment_results(comments: Iterable[Comment], sort:str, *, pins:bool=False): + """ + Sorts comments results from `files.helpers.get.get_comments_trees_eager` + :param comments: Comments to sort + :param sort: The sort to use + :param pins: Whether to sort pinned comments. Defaults to `True` + """ if sort == 'hot': ti = int(time.time()) + 3600 key_func = lambda c: ( -100000 * (c.upvotes + 1) / (pow(((ti - c.created_utc) / 1000), 1.23)), - DESC - c.created_utc + -c.created_utc ) + elif sort == 'comments': + key_func = lambda c: -c.descendant_count elif sort == 'controversial': key_func = lambda c: ( (c.upvotes + 1) / (c.downvotes + 1) + (c.downvotes + 1) / (c.upvotes + 1), - DESC - c.downvotes, - DESC - c.created_utc + -c.downvotes, + -c.created_utc ) elif sort == 'top': - key_func = lambda c: (c.downvotes - c.upvotes, DESC - c.created_utc) + key_func = lambda c: (c.downvotes - c.upvotes, -c.created_utc) elif sort == 'bottom': - key_func = lambda c: (c.upvotes - c.downvotes, DESC - c.created_utc) + key_func = lambda c: (c.upvotes - c.downvotes, -c.created_utc) elif sort == 'old': key_func = lambda c: c.created_utc else: # default, or sort == 'new' - key_func = lambda c: DESC - c.created_utc + key_func = lambda c: -c.created_utc key_func_pinned = lambda c: ( (c.is_pinned is None, c.is_pinned == '', c.is_pinned), # sort None last key_func(c)) - return sorted(comments, key=key_func_pinned) + return sorted(comments, key=key_func_pinned if pins else key_func) diff --git a/files/helpers/get.py b/files/helpers/get.py index 8bfcb48a1..68e15792d 100644 --- a/files/helpers/get.py +++ b/files/helpers/get.py @@ -1,9 +1,9 @@ from collections import defaultdict -from typing import Iterable, List, Optional, Type, Union +from typing import Callable, Iterable, List, Optional, Type, Union from flask import g from sqlalchemy import and_, or_, func -from sqlalchemy.orm import selectinload +from sqlalchemy.orm import Query, scoped_session, selectinload from files.classes import * from files.helpers.const import AUTOJANNY_ID @@ -95,6 +95,24 @@ def get_account( return user +def get_accounts_dict(ids:Union[Iterable[str], Iterable[int]], + v:Optional[User]=None, graceful=False, + include_shadowbanned=True, + db:Optional[scoped_session]=None) -> Optional[dict[int, User]]: + if not db: db = g.db + if not ids: return {} + try: + ids = set([int(id) for id in ids]) + except: + if graceful: return None + abort(404) + + users = db.query(User).filter(User.id.in_(ids)) + if not (include_shadowbanned or (v and v.can_see_shadowbanned)): + users = users.filter(User.shadowbanned == None) + users = users.all() + if len(users) != len(ids) and not graceful: abort(404) + return {u.id:u for u in users} def get_post( i:Union[str,int], @@ -277,9 +295,9 @@ def get_comments( # TODO: There is probably some way to unify this with get_comments. However, in # the interim, it's a hot path and benefits from having tailored code. def get_comment_trees_eager( - top_comment_ids:Iterable[int], - sort:str="old", - v:Optional[User]=None) -> List[Comment]: + query_filter_callable: Callable[[Query], Query], + sort: str="old", + v: Optional[User]=None) -> tuple[list[Comment], defaultdict[Comment, list[Comment]]]: if v: votes = g.db.query(CommentVote).filter_by(user_id=v.id).subquery() @@ -305,7 +323,7 @@ def get_comment_trees_eager( else: query = g.db.query(Comment) - query = query.filter(Comment.top_comment_id.in_(top_comment_ids)) + query = query_filter_callable(query) query = query.options( selectinload(Comment.author).options( selectinload(User.badges), @@ -335,13 +353,12 @@ def get_comment_trees_eager( comments_map_parent[c.parent_comment_id].append(c) for parent_id in comments_map_parent: - if parent_id is None: continue - comments_map_parent[parent_id] = sort_comment_results( - comments_map_parent[parent_id], sort) - comments_map[parent_id].replies2 = comments_map_parent[parent_id] + comments_map_parent[parent_id], sort, pins=True) + if parent_id in comments_map: + comments_map[parent_id].replies2 = comments_map_parent[parent_id] - return [comments_map[tcid] for tcid in top_comment_ids] + return comments, comments_map_parent # TODO: This function was concisely inlined into posts.py in upstream. diff --git a/files/helpers/jinja2.py b/files/helpers/jinja2.py index 20174e2c6..9332a887b 100644 --- a/files/helpers/jinja2.py +++ b/files/helpers/jinja2.py @@ -75,6 +75,7 @@ def inject_constants(): "SITE_FULL":SITE_FULL, "AUTOJANNY_ID":AUTOJANNY_ID, "NOTIFICATIONS_ID":NOTIFICATIONS_ID, + "MODMAIL_ID":MODMAIL_ID, "PUSHER_ID":PUSHER_ID, "CC":CC, "CC_TITLE":CC_TITLE, @@ -84,6 +85,10 @@ def inject_constants(): "COLORS":COLORS, "THEMES":THEMES, "PERMS":PERMS, + "FEATURES":FEATURES, + "RENDER_DEPTH_LIMIT":RENDER_DEPTH_LIMIT, + "SORTS_COMMENTS":SORTS_COMMENTS, + "SORTS_POSTS":SORTS_POSTS, } diff --git a/files/helpers/images.py b/files/helpers/media.py similarity index 94% rename from files/helpers/images.py rename to files/helpers/media.py index f7d2a5369..494b49967 100644 --- a/files/helpers/images.py +++ b/files/helpers/media.py @@ -1,10 +1,10 @@ -from PIL import Image, ImageOps -from PIL.ImageSequence import Iterator -from webptools import gifwebp import subprocess +from flask import Request +from PIL import Image, ImageOps +from webptools import gifwebp + def process_image(filename=None, resize=0): - i = Image.open(filename) if resize and i.width > resize: diff --git a/files/helpers/sanitize.py b/files/helpers/sanitize.py index 7e622abc8..17fee71db 100644 --- a/files/helpers/sanitize.py +++ b/files/helpers/sanitize.py @@ -10,21 +10,43 @@ import re from mistletoe import markdown from json import loads, dump from random import random, choice -import signal +import gevent import time import requests from files.__main__ import app -TLDS = ('ac','ad','ae','aero','af','ag','ai','al','am','an','ao','aq','ar','arpa','as','asia','at','au','aw','ax','az','ba','bb','bd','be','bf','bg','bh','bi','biz','bj','bm','bn','bo','br','bs','bt','bv','bw','by','bz','ca','cafe','cat','cc','cd','cf','cg','ch','ci','ck','cl','club','cm','cn','co','com','coop','cr','cu','cv','cx','cy','cz','de','dj','dk','dm','do','dz','ec','edu','ee','eg','er','es','et','eu','fi','fj','fk','fm','fo','fr','ga','gb','gd','ge','gf','gg','gh','gi','gl','gm','gn','gov','gp','gq','gr','gs','gt','gu','gw','gy','hk','hm','hn','hr','ht','hu','id','ie','il','im','in','info','int','io','iq','ir','is','it','je','jm','jo','jobs','jp','ke','kg','kh','ki','km','kn','kp','kr','kw','ky','kz','la','lb','lc','li','lk','lr','ls','lt','lu','lv','ly','ma','mc','md','me','mg','mh','mil','mk','ml','mm','mn','mo','mobi','mp','mq','mr','ms','mt','mu','museum','mv','mw','mx','my','mz','na','name','nc','ne','net','nf','ng','ni','nl','no','np','nr','nu','nz','om','org','pa','pe','pf','pg','ph','pk','pl','pm','pn','post','pr','pro','ps','pt','pw','py','qa','re','ro','rs','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sj','sk','sl','sm','sn','so','social','sr','ss','st','su','sv','sx','sy','sz','tc','td','tel','tf','tg','th','tj','tk','tl','tm','tn','to','tp','tr','travel','tt','tv','tw','tz','ua','ug','uk','us','uy','uz','va','vc','ve','vg','vi','vn','vu','wf','win','ws','xn','xxx','xyz','ye','yt','yu','za','zm','zw', 'moe') +TLDS = ('ac','ad','ae','aero','af','ag','ai','al','am','an','ao','aq','ar', + 'arpa','as','asia','at','au','aw','ax','az','ba','bb','bd','be','bf','bg', + 'bh','bi','biz','bj','bm','bn','bo','br','bs','bt','bv','bw','by','bz', + 'ca','cafe','cat','cc','cd','cf','cg','ch','ci','ck','cl','club','cm', + 'cn','co','com','coop','cr','cu','cv','cx','cy','cz','de','dj','dk','dm', + 'do','dz','ec','edu','ee','eg','er','es','et','eu','fi','fj','fk','fm', + 'fo','fr','ga','gb','gd','ge','gf','gg','gh','gi','gl','gm','gn','gov', + 'gp','gq','gr','gs','gt','gu','gw','gy','hk','hm','hn','hr','ht','hu', + 'id','ie','il','im','in','info','int','io','iq','ir','is','it','je','jm', + 'jo','jobs','jp','ke','kg','kh','ki','km','kn','kp','kr','kw','ky','kz', + 'la','lb','lc','li','lk','lr','ls','lt','lu','lv','ly','ma','mc','md','me', + 'mg','mh','mil','mk','ml','mm','mn','mo','mobi','mp','mq','mr','ms','mt', + 'mu','museum','mv','mw','mx','my','mz','na','name','nc','ne','net','nf', + 'ng','ni','nl','no','np','nr','nu','nz','om','org','pa','pe','pf','pg', + 'ph','pk','pl','pm','pn','post','pr','pro','ps','pt','pw','py','qa','re', + 'ro','rs','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sj','sk', + 'sl','sm','sn','so','social','sr','ss','st','su','sv','sx','sy','sz', + 'tc','td','tel','tf','tg','th','tj','tk','tl','tm','tn','to','tp','tr', + 'travel','tt','tv','tw','tz','ua','ug','uk','us','uy','uz','va','vc','ve', + 'vg','vi','vn','vu','wf','win','ws','xn','xxx','xyz','ye','yt','yu','za', + 'zm','zw', 'moe') -allowed_tags = ('b','blockquote','br','code','del','em','h1','h2','h3','h4','h5','h6','hr','i','li','ol','p','pre','strong','sub','sup','table','tbody','th','thead','td','tr','ul','a','span','ruby','rp','rt','spoiler',) +allowed_tags = ('b','blockquote','br','code','del','em','h1','h2','h3','h4', + 'h5','h6','hr','i','li','ol','p','pre','strong','sub','sup','table', + 'tbody','th','thead','td','tr','ul','a','span','ruby','rp','rt', + 'spoiler',) if app.config['MULTIMEDIA_EMBEDDING_ENABLED']: allowed_tags += ('img', 'lite-youtube', 'video', 'source',) def allowed_attributes(tag, name, value): - if name == 'style': return True if tag == 'a': @@ -123,31 +145,39 @@ def render_emoji(html, regexp, edit, marseys_used=set(), b=False): return html -def with_sigalrm_timeout(timeout: int): - 'Use SIGALRM to raise an exception if the function executes for longer than timeout seconds' - - # while trying to test this using time.sleep I discovered that gunicorn does in fact do some - # async so if we timeout on that (or on a db op) then the process is crashed without returning - # a proper 500 error. Oh well. - def sig_handler(signum, frame): - print("Timeout!", flush=True) - raise Exception("Timeout") - +def with_gevent_timeout(timeout: int): + ''' + Use gevent to raise an exception if the function executes for longer than timeout seconds + Using gevent instead of a signal based approach allows for proper async and avoids some + worker crashes + ''' def inner(func): - @functools.wraps(inner) + @functools.wraps(func) def wrapped(*args, **kwargs): - signal.signal(signal.SIGALRM, sig_handler) - signal.alarm(timeout) - try: - return func(*args, **kwargs) - finally: - signal.alarm(0) + return gevent.with_timeout(timeout, func, *args, **kwargs) return wrapped return inner -@with_sigalrm_timeout(2) -def sanitize(sanitized, alert=False, comment=False, edit=False): +REMOVED_CHARACTERS = ['\u200e', '\u200b', '\ufeff'] +""" +Characters which are removed from content +""" +def sanitize_raw(sanitized:Optional[str], allow_newlines:bool, length_limit:Optional[int]) -> str: + if not sanitized: return "" + for char in REMOVED_CHARACTERS: + sanitized = sanitized.replace(char, '') + if allow_newlines: + sanitized = sanitized.replace("\r\n", "\n") + else: + sanitized = sanitized.replace("\r","").replace("\n", "") + sanitized = sanitized.strip() + if length_limit is not None: + sanitized = sanitized[:length_limit] + return sanitized + +@with_gevent_timeout(2) +def sanitize(sanitized, alert=False, comment=False, edit=False): # double newlines, eg. hello\nworld becomes hello\n\nworld, which later becomes

hello

world

sanitized = linefeeds_regex.sub(r'\1\n\n\2', sanitized) @@ -186,15 +216,11 @@ def sanitize(sanitized, alert=False, comment=False, edit=False): sanitized = sub_regex.sub(r'\1/\2', sanitized) matches = [ m for m in mention_regex.finditer(sanitized) if m ] - names = set( m.group(2) for m in matches ) + names = set(m.group(2) for m in matches) users = get_users(names,graceful=True) if len(users) > app.config['MENTION_LIMIT']: - signal.alarm(0) - abort( - make_response( - jsonify( - error=f'Mentioned {len(users)} users but limit is {app.config["MENTION_LIMIT"]}'), 400)) + abort(400, f'Mentioned {len(users)} users but limit is {app.config["MENTION_LIMIT"]}') for u in users: if not u: continue @@ -281,12 +307,8 @@ def sanitize(sanitized, alert=False, comment=False, edit=False): sanitized = sanitized.replace('&','&') sanitized = utm_regex.sub('', sanitized) sanitized = utm_regex2.sub('', sanitized) - - sanitized = sanitized.replace('','').replace('','') - - sanitized = bleach.Cleaner(tags=allowed_tags, attributes=allowed_attributes, protocols=['http', 'https'], @@ -321,17 +343,11 @@ def sanitize(sanitized, alert=False, comment=False, edit=False): domain_list.add(new_domain) bans = g.db.query(BannedDomain.domain).filter(BannedDomain.domain.in_(list(domain_list))).all() - if bans: abort(403, description=f"Remove the banned domains {bans} and try again!") - return sanitized - - - def allowed_attributes_emojis(tag, name, value): - if tag == 'img': if name == 'loading' and value == 'lazy': return True if name == 'data-bs-toggle' and value == 'tooltip': return True @@ -339,9 +355,8 @@ def allowed_attributes_emojis(tag, name, value): return False -@with_sigalrm_timeout(1) +@with_gevent_timeout(1) def filter_emojis_only(title, edit=False, graceful=False): - title = unwanted_bytes_regex.sub('', title) title = whitespace_regex.sub(' ', title) title = html.escape(title, quote=True) diff --git a/files/helpers/services.py b/files/helpers/services.py new file mode 100644 index 000000000..0a1a14fa1 --- /dev/null +++ b/files/helpers/services.py @@ -0,0 +1,59 @@ +import sys + +import gevent +from pusher_push_notifications import PushNotifications +from sqlalchemy.orm import scoped_session + +from files.classes.leaderboard import (LeaderboardMeta, ReceivedDownvotesLeaderboard, + GivenUpvotesLeaderboard) +from files.helpers.assetcache import assetcache_path +from files.helpers.const import PUSHER_ID, PUSHER_KEY, SITE_FULL, SITE_ID +from files.__main__ import app, db_session + +if PUSHER_ID != 'blahblahblah': + beams_client = PushNotifications(instance_id=PUSHER_ID, secret_key=PUSHER_KEY) +else: + beams_client = None + +def pusher_thread2(interests, notifbody, username): + if not beams_client: return + beams_client.publish_to_interests( + interests=[interests], + publish_body={ + 'web': { + 'notification': { + 'title': f'New message from @{username}', + 'body': notifbody, + 'deep_link': f'{SITE_FULL}/notifications?messages=true', + 'icon': SITE_FULL + assetcache_path(f'images/{SITE_ID}/icon.webp'), + } + }, + 'fcm': { + 'notification': { + 'title': f'New message from @{username}', + 'body': notifbody, + }, + 'data': { + 'url': '/notifications?messages=true', + } + } + }, + ) + sys.stdout.flush() + +_lb_received_downvotes_meta = LeaderboardMeta("Downvotes", "received downvotes", "received-downvotes", "downvotes", "downvoted") +_lb_given_upvotes_meta = LeaderboardMeta("Upvotes", "given upvotes", "given-upvotes", "upvotes", "upvoting") + +def leaderboard_thread(): + global lb_downvotes_received, lb_upvotes_given + + db:scoped_session = db_session() # type: ignore + + lb_downvotes_received = ReceivedDownvotesLeaderboard(_lb_received_downvotes_meta, db) + lb_upvotes_given = GivenUpvotesLeaderboard(_lb_given_upvotes_meta, db) + + db.close() + sys.stdout.flush() + +if app.config["ENABLE_SERVICES"]: + gevent.spawn(leaderboard_thread()) diff --git a/files/helpers/wrappers.py b/files/helpers/wrappers.py index 533582aa7..f61bb0b42 100644 --- a/files/helpers/wrappers.py +++ b/files/helpers/wrappers.py @@ -25,7 +25,7 @@ def get_logged_in_user(): lo_user = session.get("lo_user") if lo_user: id = int(lo_user) - v = g.db.query(User).get(id) + v = g.db.get(User, id) if v: v.client = None nonce = session.get("login_nonce", 0) diff --git a/files/routes/__init__.py b/files/routes/__init__.py index abd02add8..407a0e890 100644 --- a/files/routes/__init__.py +++ b/files/routes/__init__.py @@ -14,7 +14,8 @@ from .static import * from .users import * from .votes import * from .feeds import * -from .awards import * +if FEATURES['AWARDS']: + from .awards import * # disable entirely pending possible future use of coins from .volunteer import * if app.debug: from .dev import * diff --git a/files/routes/admin.py b/files/routes/admin.py index fc7c8d64b..22c58c52a 100644 --- a/files/routes/admin.py +++ b/files/routes/admin.py @@ -1,13 +1,11 @@ import time -from os import remove -from PIL import Image as IMAGE from files.helpers.wrappers import * from files.helpers.alerts import * from files.helpers.sanitize import * from files.helpers.security import * from files.helpers.get import * -from files.helpers.images import * +from files.helpers.media import * from files.helpers.const import * from files.classes import * from flask import * @@ -16,7 +14,6 @@ from .front import frontlist from files.helpers.comments import comment_on_publish, comment_on_unpublish from datetime import datetime import requests -from urllib.parse import quote, urlencode month = datetime.now().strftime('%B') @@ -276,12 +273,12 @@ def update_filter_status(v): return { 'result': f'Status of {new_status} is not permitted' } if post_id: - p = g.db.query(Submission).get(post_id) + p = g.db.get(Submission, post_id) old_status = p.filter_state rows_updated = g.db.query(Submission).where(Submission.id == post_id) \ .update({Submission.filter_state: new_status}) elif comment_id: - c = g.db.query(Comment).get(comment_id) + c = g.db.get(Comment, comment_id) old_status = c.filter_state rows_updated = g.db.query(Comment).where(Comment.id == comment_id) \ .update({Comment.filter_state: new_status}) @@ -414,7 +411,7 @@ def change_settings(v, setting): parent_submission=None, level=1, body_html=body_html, - sentto=2, + sentto=MODMAIL_ID, distinguish_level=6 ) g.db.add(new_comment) @@ -735,13 +732,12 @@ def alt_votes_get(v): @limiter.exempt @admin_level_required(2) def admin_link_accounts(v): - - u1 = int(request.values.get("u1")) - u2 = int(request.values.get("u2")) + u1 = get_account(request.values.get("u1", '')) + u2 = get_account(request.values.get("u2", '')) new_alt = Alt( - user1=u1, - user2=u2, + user1=u1.id, + user2=u2.id, is_manual=True ) @@ -756,7 +752,7 @@ def admin_link_accounts(v): g.db.add(ma) g.db.commit() - return redirect(f"/admin/alt_votes?u1={g.db.query(User).get(u1).username}&u2={g.db.query(User).get(u2).username}") + return redirect(f"/admin/alt_votes?u1={u1.id}&u2={u2.id}") @app.get("/admin/removed/posts") @@ -1225,10 +1221,9 @@ def sticky_post(post_id, v): @limiter.exempt @admin_level_required(2) def unsticky_post(post_id, v): - post = g.db.query(Submission).filter_by(id=post_id).one_or_none() if post and post.stickied: - if post.stickied.endswith('(pin award)'): abort(403, "Can't unpin award pins!") + if FEATURES['AWARDS'] and post.stickied.endswith('(pin award)'): abort(403, "Can't unpin award pins!") post.stickied = None post.stickied_utc = None @@ -1252,7 +1247,6 @@ def unsticky_post(post_id, v): @limiter.exempt @admin_level_required(2) def sticky_comment(cid, v): - comment = get_comment(cid, v=v) if not comment.is_pinned: @@ -1278,11 +1272,10 @@ def sticky_comment(cid, v): @limiter.exempt @admin_level_required(2) def unsticky_comment(cid, v): - comment = get_comment(cid, v=v) if comment.is_pinned: - if comment.is_pinned.endswith("(pin award)"): abort(403, "Can't unpin award pins!") + if FEATURES['AWARDS'] and comment.is_pinned.endswith("(pin award)"): abort(403, "Can't unpin award pins!") comment.is_pinned = None g.db.add(comment) diff --git a/files/routes/awards.py b/files/routes/awards.py index fd4c3d9c8..817198754 100644 --- a/files/routes/awards.py +++ b/files/routes/awards.py @@ -15,7 +15,7 @@ from copy import deepcopy def shop(v): abort(404) # disable entirely pending possible future use of coins - AWARDS = deepcopy(AWARDS2) + AWARDS = deepcopy(AWARDS_ENABLED) for val in AWARDS.values(): val["owned"] = 0 @@ -41,7 +41,7 @@ def buy(v, award): if award == 'ghost' and v.admin_level < 2: abort(403, "Only admins can buy that award.") - AWARDS = deepcopy(AWARDS2) + AWARDS = deepcopy(AWARDS_ENABLED) if award not in AWARDS: abort(400) og_price = AWARDS[award]["price"] @@ -50,7 +50,6 @@ def buy(v, award): if request.values.get("mb"): if v.procoins < price: abort(400, "Not enough marseybux.") - if award == "grass": abort(403, "You can't buy the grass award with marseybux.") v.procoins -= price else: if v.coins < price: abort(400, "Not enough coins.") @@ -85,33 +84,8 @@ def buy(v, award): g.db.add(v) - if award == "lootbox": - send_repeatable_notification(995, f"@{v.username} bought a lootbox!") - for i in [1,2,3,4,5]: - award = random.choice(["snow", "gingerbread", "lights", "candycane", "fireplace"]) - award = AwardRelationship(user_id=v.id, kind=award) - g.db.add(award) - g.db.flush() - v.lootboxes_bought += 1 - if v.lootboxes_bought == 10 and not v.has_badge(76): - new_badge = Badge(badge_id=76, user_id=v.id) - g.db.add(new_badge) - g.db.flush() - send_notification(v.id, f"@AutoJanny has given you the following profile badge:\n\n![]({new_badge.path})\n\n{new_badge.name}") - elif v.lootboxes_bought == 50 and not v.has_badge(77): - new_badge = Badge(badge_id=77, user_id=v.id) - g.db.add(new_badge) - g.db.flush() - send_notification(v.id, f"@AutoJanny has given you the following profile badge:\n\n![]({new_badge.path})\n\n{new_badge.name}") - elif v.lootboxes_bought == 150 and not v.has_badge(78): - new_badge = Badge(badge_id=78, user_id=v.id) - g.db.add(new_badge) - g.db.flush() - send_notification(v.id, f"@AutoJanny has given you the following profile badge:\n\n![]({new_badge.path})\n\n{new_badge.name}") - - else: - award_object = AwardRelationship(user_id=v.id, kind=award) - g.db.add(award_object) + award_object = AwardRelationship(user_id=v.id, kind=award) + g.db.add(award_object) g.db.add(v) g.db.commit() @@ -161,54 +135,6 @@ def award_post(pid, v): if note: msg += f"\n\n> {note}" send_repeatable_notification(author.id, msg) - if kind == "ban": - link = f"[this post]({post.shortlink})" - - if not author.is_suspended: - author.ban(reason=f"1-Day ban award used by @{v.username} on /post/{post.id}", days=1) - send_repeatable_notification(author.id, f"Your account has been banned for **a day** for {link}. It sucked and you should feel bad.") - elif author.unban_utc: - author.unban_utc += 86400 - send_repeatable_notification(author.id, f"Your account has been banned for **yet another day** for {link}. Seriously man?") - elif kind == "unban": - if not author.is_suspended or not author.unban_utc or time.time() > author.unban_utc: abort(403) - - if author.unban_utc - time.time() > 86400: - author.unban_utc -= 86400 - send_repeatable_notification(author.id, "Your ban duration has been reduced by 1 day!") - else: - author.unban_utc = 0 - author.is_banned = 0 - author.ban_evade = 0 - send_repeatable_notification(author.id, "You have been unbanned!") - elif kind == "pin": - if post.stickied and post.stickied_utc: - post.stickied_utc += 3600 - else: - post.stickied = f'{v.username} (pin award)' - post.stickied_utc = int(time.time()) + 3600 - g.db.add(post) - cache.delete_memoized(frontlist) - elif kind == "unpin": - if not post.stickied_utc: abort(403) - t = post.stickied_utc - 3600 - if time.time() > t: - post.stickied = None - post.stickied_utc = None - cache.delete_memoized(frontlist) - else: post.stickied_utc = t - g.db.add(post) - elif kind == "benefactor": - author.patron = 1 - if author.patron_utc: author.patron_utc += 2629746 - else: author.patron_utc = int(time.time()) + 2629746 - author.procoins += 2500 - if not v.has_badge(103): - badge = Badge(user_id=v.id, badge_id=103) - g.db.add(badge) - g.db.flush() - send_notification(v.id, f"@AutoJanny has given you the following profile badge:\n\n![]({badge.path})\n\n{badge.name}") - if author.received_award_count: author.received_award_count += 1 else: author.received_award_count = 1 g.db.add(author) @@ -260,54 +186,6 @@ def award_comment(cid, v): if note: msg += f"\n\n> {note}" send_repeatable_notification(author.id, msg) - if kind == "benefactor" and author.id == v.id: - abort(400, "You can't use this award on yourself.") - - if kind == "ban": - link = f"[this comment]({c.shortlink})" - - if not author.is_suspended: - author.ban(reason=f"1-Day ban award used by @{v.username} on /comment/{c.id}", days=1) - send_repeatable_notification(author.id, f"Your account has been banned for **a day** for {link}. It sucked and you should feel bad.") - elif author.unban_utc: - author.unban_utc += 86400 - send_repeatable_notification(author.id, f"Your account has been banned for **yet another day** for {link}. Seriously man?") - elif kind == "unban": - if not author.is_suspended or not author.unban_utc or time.time() > author.unban_utc: abort(403) - - if author.unban_utc - time.time() > 86400: - author.unban_utc -= 86400 - send_repeatable_notification(author.id, "Your ban duration has been reduced by 1 day!") - else: - author.unban_utc = 0 - author.is_banned = 0 - author.ban_evade = 0 - send_repeatable_notification(author.id, "You have been unbanned!") - elif kind == "pin": - if c.is_pinned and c.is_pinned_utc: c.is_pinned_utc += 3600 - else: - c.is_pinned = f'{v.username} (pin award)' - c.is_pinned_utc = int(time.time()) + 3600 - g.db.add(c) - elif kind == "unpin": - if not c.is_pinned_utc: abort(403) - t = c.is_pinned_utc - 3600 - if time.time() > t: - c.is_pinned = None - c.is_pinned_utc = None - else: c.is_pinned_utc = t - g.db.add(c) - elif kind == "benefactor": - author.patron = 1 - if author.patron_utc: author.patron_utc += 2629746 - else: author.patron_utc = int(time.time()) + 2629746 - author.procoins += 2500 - if not v.has_badge(103): - badge = Badge(user_id=v.id, badge_id=103) - g.db.add(badge) - g.db.flush() - send_notification(v.id, f"@AutoJanny has given you the following profile badge:\n\n![]({badge.path})\n\n{badge.name}") - if author.received_award_count: author.received_award_count += 1 else: author.received_award_count = 1 g.db.add(author) @@ -323,7 +201,7 @@ def admin_userawards_get(v): abort(404) # disable entirely pending possible future use of coins if v.admin_level != 3: - return render_template("admin/awards.html", awards=list(AWARDS3.values()), v=v) + return render_template("admin/awards.html", awards=list(AWARDS_JL2_PRINTABLE.values()), v=v) return render_template("admin/awards.html", awards=list(AWARDS.values()), v=v) @@ -335,22 +213,15 @@ def admin_userawards_post(v): try: u = request.values.get("username").strip() except: abort(404) - - whitelist = ("shit", "fireflies", "train", "scooter", "wholesome", "glowie") - + whitelist = () u = get_user(u, graceful=False, v=v) - notify_awards = {} for key, value in request.values.items(): if key not in AWARDS: continue - if v.admin_level < 3 and key not in whitelist: continue - if value: - if int(value) > 10: abort(403) - if int(value): notify_awards[key] = int(value) for x in range(int(value)): @@ -358,7 +229,6 @@ def admin_userawards_post(v): user_id=u.id, kind=key ) - g.db.add(award) if v.id != u.id: @@ -384,5 +254,9 @@ def admin_userawards_post(v): g.db.commit() - if v.admin_level != 3: return render_template("admin/awards.html", awards=list(AWARDS3.values()), v=v) - return render_template("admin/awards.html", awards=list(AWARDS.values()), v=v) + if v.admin_level < 3: + awards: dict = AWARDS_JL2_PRINTABLE + else: + awards: dict = AWARDS + + return render_template("admin/awards.html", awards=awards, v=v) diff --git a/files/routes/comments.py b/files/routes/comments.py index 2ba236304..e5ae9f5c3 100644 --- a/files/routes/comments.py +++ b/files/routes/comments.py @@ -1,6 +1,6 @@ from files.helpers.wrappers import * from files.helpers.alerts import * -from files.helpers.images import * +from files.helpers.media import process_image from files.helpers.const import * from files.helpers.comments import comment_on_publish from files.classes import * @@ -110,7 +110,7 @@ def post_pid_comment_cid(cid, pid=None, anything=None, v=None, sub=None): def api_comment(v): if v.is_suspended: abort(403, "You can't perform this action while banned.") - parent_fullname = request.values.get("parent_fullname").strip() + parent_fullname = request.values.get("parent_fullname", "").strip() if len(parent_fullname) < 4: abort(400) id = parent_fullname[3:] @@ -129,9 +129,9 @@ def api_comment(v): if not parent_post: abort(404) # don't allow sending comments to the ether level = 1 if isinstance(parent, Submission) else parent.level + 1 - body = request.values.get("body", "").strip()[:10000] - - if not body and not request.files.get('file'): abort(400, "You need to actually write something!") + body = sanitize_raw(request.values.get("body"), allow_newlines=True, length_limit=10000) + if not body and not request.files.get('file'): + abort(400, "You need to actually write something!") if request.files.get("file") and request.headers.get("cf-ipcountry") != "T1": files = request.files.getlist('file')[:4] @@ -147,22 +147,7 @@ def api_comment(v): body += f"\n\n![]({image})" else: body += f'\n\n{image}' - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - if app.config['MULTIMEDIA_EMBEDDING_ENABLED']: - body += f"\n\n{url}" - else: - body += f'\n\n{url}' - else: abort(400, "Image/Video files only") + else: abort(400, "Image files only") body_html = sanitize(body, comment=True) @@ -269,12 +254,9 @@ def api_comment(v): @limiter.limit("1/second;30/minute;200/hour;1000/day") @auth_required def edit_comment(cid, v): - c = get_comment(cid, v=v) - if c.author_id != v.id: abort(403) - - body = request.values.get("body", "").strip()[:10000] + body = sanitize_raw(request.values.get("body"), allow_newlines=True, length_limit=10000) if len(body) < 1 and not (request.files.get("file") and request.headers.get("cf-ipcountry") != "T1"): abort(400, "You have to actually type something!") @@ -325,19 +307,7 @@ def edit_comment(cid, v): file.save(name) url = process_image(name) body += f"\n\n![]({url})" - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - body += f"\n\n{url}" - else: abort(400, "Image/Video files only") + else: abort(400, "Image files only") body_html = sanitize(body, edit=True) diff --git a/files/routes/errors.py b/files/routes/errors.py index 01f00f4ad..76f37842d 100644 --- a/files/routes/errors.py +++ b/files/routes/errors.py @@ -1,15 +1,18 @@ -from files.helpers.wrappers import * -from flask import request, session -from urllib.parse import quote, urlencode import time -from files.__main__ import app from http.client import responses +from urllib.parse import quote, urlencode + +from flask import g, redirect, render_template, request, session + +from files.helpers.const import ERROR_MESSAGES, SITE_FULL, WERKZEUG_ERROR_DESCRIPTIONS +from files.__main__ import app @app.errorhandler(400) @app.errorhandler(401) @app.errorhandler(403) @app.errorhandler(404) @app.errorhandler(405) +@app.errorhandler(409) @app.errorhandler(413) @app.errorhandler(422) @app.errorhandler(429) diff --git a/files/routes/front.py b/files/routes/front.py index 4717ae9be..b96131f86 100644 --- a/files/routes/front.py +++ b/files/routes/front.py @@ -1,9 +1,13 @@ +from sqlalchemy.orm import Query + from files.helpers.wrappers import * from files.helpers.get import * from files.helpers.strings import sql_ilike_clean from files.__main__ import app, cache, limiter from files.classes.submission import Submission -from files.helpers.contentsorting import apply_time_filter, sort_objects +from files.helpers.comments import comment_filter_moderated +from files.helpers.contentsorting import \ + apply_time_filter, sort_objects, sort_comment_results defaulttimefilter = environ.get("DEFAULT_TIME_FILTER", "all").strip() @@ -47,7 +51,7 @@ def notifications(v): posts = request.values.get('posts') reddit = request.values.get('reddit') if modmail and v.admin_level > 1: - comments = g.db.query(Comment).filter(Comment.sentto==2).order_by(Comment.id.desc()).offset(25*(page-1)).limit(26).all() + comments = g.db.query(Comment).filter(Comment.sentto == MODMAIL_ID).order_by(Comment.id.desc()).offset(25*(page-1)).limit(26).all() next_exists = (len(comments) > 25) listing = comments[:25] elif messages: @@ -347,9 +351,7 @@ def changeloglist(v=None, sort="new", page=1, t="all", site=None): @app.get("/random_post") -@auth_desired -def random_post(v): - +def random_post(): p = g.db.query(Submission.id).filter(Submission.deleted_utc == 0, Submission.is_banned == False, Submission.private == False).order_by(func.random()).first() if p: p = p[0] @@ -359,8 +361,7 @@ def random_post(v): @app.get("/random_user") -@auth_desired -def random_user(v): +def random_user(): u = g.db.query(User.username).order_by(func.random()).first() if u: u = u[0] @@ -372,27 +373,31 @@ def random_user(v): @app.get("/comments") @auth_required def all_comments(v): - try: page = max(int(request.values.get("page", 1)), 1) - except: page = 1 - - sort=request.values.get("sort", "new") - t=request.values.get("t", defaulttimefilter) - - try: gt=int(request.values.get("after", 0)) - except: gt=0 - - try: lt=int(request.values.get("before", 0)) - except: lt=0 - - idlist = get_comments_idlist(v=v, page=page, sort=sort, t=t, gt=gt, lt=lt) - comments = get_comments(idlist, v=v) + page = max(request.values.get("page", 1, int), 1) + sort = request.values.get("sort", "new") + time_filter = request.values.get("t", defaulttimefilter) + time_gt = request.values.get("after", 0, int) + time_lt = request.values.get("before", 0, int) + idlist = get_comments_idlist(v=v, + page=page, sort=sort, t=time_filter, gt=time_gt, lt=time_lt) next_exists = len(idlist) > 25 - idlist = idlist[:25] - if request.headers.get("Authorization"): return {"data": [x.json for x in comments]} - return render_template("home_comments.html", v=v, sort=sort, t=t, page=page, comments=comments, standalone=True, next_exists=next_exists) + def comment_tree_filter(q: Query) -> Query: + q = q.filter(Comment.id.in_(idlist)) + q = comment_filter_moderated(q, v) + q = q.options(selectinload(Comment.post)) # used for post titles + return q + + comments, _ = get_comment_trees_eager(comment_tree_filter, sort=sort, v=v) + comments = sort_comment_results(comments, sort=sort, pins=False) + + if request.headers.get("Authorization"): + return {"data": [x.json for x in comments]} + return render_template("home_comments.html", v=v, + sort=sort, t=time_filter, page=page, next_exists=next_exists, + comments=comments, standalone=True) def get_comments_idlist(page=1, v=None, sort="new", t="all", gt=0, lt=0): diff --git a/files/routes/login.py b/files/routes/login.py index 20d5b08a9..81f9a32b4 100644 --- a/files/routes/login.py +++ b/files/routes/login.py @@ -2,12 +2,11 @@ from urllib.parse import urlencode from files.mail import * from files.__main__ import app, limiter from files.helpers.const import * -import requests +from files.helpers.captcha import validate_captcha @app.get("/login") @auth_desired def login_get(v): - redir = request.values.get("redirect") if redir: redir = redir.replace("/logged_out", "").strip() @@ -289,21 +288,11 @@ def sign_up_post(v): if existing_account: return signup_error("An account with that username already exists.") - - if app.config.get("HCAPTCHA_SITEKEY"): - token = request.values.get("h-captcha-response") - if not token: - return signup_error("Unable to verify captcha [1].") - - data = {"secret": app.config["HCAPTCHA_SECRET"], - "response": token, - "sitekey": app.config["HCAPTCHA_SITEKEY"]} - url = "https://hcaptcha.com/siteverify" - - x = requests.post(url, data=data, timeout=5) - - if not x.json()["success"]: - return signup_error("Unable to verify captcha [2].") + + if not validate_captcha(app.config.get("HCAPTCHA_SECRET", ""), + app.config.get("HCAPTCHA_SITEKEY", ""), + request.values.get("h-captcha-response", "")): + return signup_error("Unable to verify CAPTCHA") session.pop("signup_token") diff --git a/files/routes/oauth.py b/files/routes/oauth.py index 314290f0f..e684bc0cf 100644 --- a/files/routes/oauth.py +++ b/files/routes/oauth.py @@ -61,7 +61,7 @@ def request_api_keys(v): parent_submission=None, level=1, body_html=body_html, - sentto=2, + sentto=MODMAIL_ID, distinguish_level=6 ) g.db.add(new_comment) diff --git a/files/routes/posts.py b/files/routes/posts.py index f0ca197a4..09c62ed09 100644 --- a/files/routes/posts.py +++ b/files/routes/posts.py @@ -3,8 +3,10 @@ import gevent from files.helpers.wrappers import * from files.helpers.sanitize import * from files.helpers.alerts import * +from files.helpers.comments import comment_filter_moderated from files.helpers.contentsorting import sort_objects from files.helpers.const import * +from files.helpers.media import process_image from files.helpers.strings import sql_ilike_clean from files.classes import * from flask import * @@ -17,6 +19,7 @@ from os import path import requests from shutil import copyfile from sys import stdout +from sqlalchemy.orm import Query snappyquotes = [f':#{x}:' for x in marseys_const2] @@ -129,102 +132,39 @@ def post_id(pid, anything=None, v=None): if post.club and not (v and (v.paid_dues or v.id == post.author_id)): abort(403) - if v: - votes = g.db.query(CommentVote).filter_by(user_id=v.id).subquery() - blocking = v.blocking.subquery() - blocked = v.blocked.subquery() - - comments = g.db.query( - Comment, - votes.c.vote_type, - blocking.c.target_id, - blocked.c.target_id, - ) - - if not (v and v.shadowbanned) and not (v and v.admin_level > 2): - comments = comments.join(User, User.id == Comment.author_id).filter(User.shadowbanned == None) - - if v.admin_level < 2: - filter_clause = ((Comment.filter_state != 'filtered') & (Comment.filter_state != 'removed')) | (Comment.author_id == v.id) - comments = comments.filter(filter_clause) - - comments=comments.filter(Comment.parent_submission == post.id).join( - votes, - votes.c.comment_id == Comment.id, - isouter=True - ).join( - blocking, - blocking.c.target_id == Comment.author_id, - isouter=True - ).join( - blocked, - blocked.c.user_id == Comment.author_id, - isouter=True - ) - - output = [] - for c in comments.all(): - comment = c[0] - comment.voted = c[1] or 0 - comment.is_blocking = c[2] or 0 - comment.is_blocked = c[3] or 0 - output.append(comment) - - pinned = [c[0] for c in comments.filter(Comment.is_pinned != None).all()] - - comments = comments.filter(Comment.level == 1, Comment.is_pinned == None) - comments = sort_objects(comments, sort, Comment) - comments = [c[0] for c in comments.all()] - else: - pinned = g.db.query(Comment).filter(Comment.parent_submission == post.id, Comment.is_pinned != None).all() - - comments = g.db.query(Comment).join(User, User.id == Comment.author_id).filter(User.shadowbanned == None, Comment.parent_submission == post.id, Comment.level == 1, Comment.is_pinned == None) - comments = sort_objects(comments, sort, Comment) - - filter_clause = (Comment.filter_state != 'filtered') & (Comment.filter_state != 'removed') - comments = comments.filter(filter_clause) - - comments = comments.all() - - offset = 0 - ids = set() - limit = app.config['RESULTS_PER_PAGE_COMMENTS'] + offset = 0 - if post.comment_count > limit and not request.headers.get("Authorization") and not request.values.get("all"): - comments2 = [] - count = 0 - if post.created_utc > 1638672040: - for comment in comments: - comments2.append(comment) - ids.add(comment.id) - count += g.db.query(Comment.id).filter_by(parent_submission=post.id, top_comment_id=comment.id).count() + 1 - if count > limit: break - else: - for comment in comments: - comments2.append(comment) - ids.add(comment.id) - count += g.db.query(Comment.id).filter_by(parent_submission=post.id, parent_comment_id=comment.id).count() + 1 - if count > limit: break + top_comments = g.db.query(Comment.id, Comment.descendant_count).filter( + Comment.parent_submission == post.id, + Comment.level == 1, + ).order_by(Comment.is_pinned.desc().nulls_last()) + top_comments = comment_filter_moderated(top_comments, v) + top_comments = sort_objects(top_comments, sort, Comment) - if len(comments) == len(comments2): offset = 0 - else: offset = 1 - comments = comments2 + pg_top_comment_ids = [] + pg_comment_qty = 0 + for tc_id, tc_children_qty in top_comments.all(): + if pg_comment_qty >= limit: + offset = 1 + break + pg_comment_qty += tc_children_qty + 1 + pg_top_comment_ids.append(tc_id) - for pin in pinned: - if pin.is_pinned_utc and int(time.time()) > pin.is_pinned_utc: - pin.is_pinned = None - pin.is_pinned_utc = None - g.db.add(pin) - pinned.remove(pin) + def comment_tree_filter(q: Query) -> Query: + q = q.filter(Comment.top_comment_id.in_(pg_top_comment_ids)) + q = comment_filter_moderated(q, v) + return q - top_comments = pinned + comments - top_comment_ids = [c.id for c in top_comments] - post.replies = get_comment_trees_eager(top_comment_ids, sort, v) + comments, comment_tree = get_comment_trees_eager(comment_tree_filter, sort, v) + post.replies = comment_tree[None] # parent=None -> top-level comments + ids = {c.id for c in post.replies} post.views += 1 + g.db.expire_on_commit = False g.db.add(post) g.db.commit() + g.db.expire_on_commit = True if request.headers.get("Authorization"): return post.json else: @@ -239,95 +179,52 @@ def viewmore(v, pid, sort, offset): post = get_post(pid, v=v) if post.club and not (v and (v.paid_dues or v.id == post.author_id)): abort(403) - offset = int(offset) + offset_prev = int(offset) try: ids = set(int(x) for x in request.values.get("ids").split(',')) except: abort(400) - if sort == "new": - newest = g.db.query(Comment).filter(Comment.id.in_(ids)).order_by(Comment.created_utc.desc()).first() - - if v: - votes = g.db.query(CommentVote).filter_by(user_id=v.id).subquery() - - blocking = v.blocking.subquery() - - blocked = v.blocked.subquery() - - comments = g.db.query( - Comment, - votes.c.vote_type, - blocking.c.target_id, - blocked.c.target_id, - ).filter(Comment.parent_submission == pid, Comment.is_pinned == None, Comment.id.notin_(ids)) - - if not (v and v.shadowbanned) and not (v and v.admin_level > 2): - comments = comments.join(User, User.id == Comment.author_id).filter(User.shadowbanned == None) - - if not v or v.admin_level < 2: - filter_clause = (Comment.filter_state != 'filtered') & (Comment.filter_state != 'removed') - if v: - filter_clause = filter_clause | (Comment.author_id == v.id) - comments = comments.filter(filter_clause) - - comments=comments.join( - votes, - votes.c.comment_id == Comment.id, - isouter=True - ).join( - blocking, - blocking.c.target_id == Comment.author_id, - isouter=True - ).join( - blocked, - blocked.c.user_id == Comment.author_id, - isouter=True - ) - - output = [] - for c in comments.all(): - comment = c[0] - comment.voted = c[1] or 0 - comment.is_blocking = c[2] or 0 - comment.is_blocked = c[3] or 0 - output.append(comment) - - comments = comments.filter(Comment.level == 1) - - if sort == "new": - comments = comments.filter(Comment.created_utc < newest.created_utc) - comments = sort_objects(comments, sort, Comment) - - comments = [c[0] for c in comments.all()] - else: - comments = g.db.query(Comment).join(User, User.id == Comment.author_id).filter(User.shadowbanned == None, Comment.parent_submission == pid, Comment.level == 1, Comment.is_pinned == None, Comment.id.notin_(ids)) - - if sort == "new": - comments = comments.filter(Comment.created_utc < newest.created_utc) - comments = sort_objects(comments, sort, Comment) - - comments = comments.all() - comments = comments[offset:] - limit = app.config['RESULTS_PER_PAGE_COMMENTS'] - comments2 = [] - count = 0 + offset = 0 - if post.created_utc > 1638672040: - for comment in comments: - comments2.append(comment) - ids.add(comment.id) - count += g.db.query(Comment.id).filter_by(parent_submission=post.id, top_comment_id=comment.id).count() + 1 - if count > limit: break - else: - for comment in comments: - comments2.append(comment) - ids.add(comment.id) - count += g.db.query(Comment.id).filter_by(parent_submission=post.id, parent_comment_id=comment.id).count() + 1 - if count > limit: break - - if len(comments) == len(comments2): offset = 0 - else: offset += 1 - comments = comments2 + # TODO: Unify with common post_id logic + top_comments = g.db.query(Comment.id, Comment.descendant_count).filter( + Comment.parent_submission == post.id, + Comment.level == 1, + Comment.id.notin_(ids), + Comment.is_pinned == None, + ).order_by(Comment.is_pinned.desc().nulls_last()) + + if sort == "new": + newest_created_utc = g.db.query(Comment.created_utc).filter( + Comment.id.in_(ids), + Comment.is_pinned == None, + ).order_by(Comment.created_utc.desc()).limit(1).scalar() + + # Needs to be <=, not just <, to support seed_db data which has many identical + # created_utc values. Shouldn't cause duplication in real data because of the + # `NOT IN :ids` in top_comments. + top_comments = top_comments.filter(Comment.created_utc <= newest_created_utc) + + top_comments = comment_filter_moderated(top_comments, v) + top_comments = sort_objects(top_comments, sort, Comment) + + pg_top_comment_ids = [] + pg_comment_qty = 0 + for tc_id, tc_children_qty in top_comments.all(): + if pg_comment_qty >= limit: + offset = offset_prev + 1 + break + pg_comment_qty += tc_children_qty + 1 + pg_top_comment_ids.append(tc_id) + + def comment_tree_filter(q: Query) -> Query: + q = q.filter(Comment.top_comment_id.in_(pg_top_comment_ids)) + q = comment_filter_moderated(q, v) + return q + + _, comment_tree = get_comment_trees_eager(comment_tree_filter, sort, v) + comments = comment_tree[None] # parent=None -> top-level comments + ids |= {c.id for c in comments} return render_template("comments.html", v=v, comments=comments, p=post, ids=list(ids), render_replies=True, pid=pid, sort=sort, offset=offset, ajax=True) @@ -353,7 +250,7 @@ def morecomments(v, cid): votes.c.vote_type, blocking.c.target_id, blocked.c.target_id, - ).filter(Comment.top_comment_id == tcid, Comment.level > 9).join( + ).filter(Comment.top_comment_id == tcid, Comment.level > RENDER_DEPTH_LIMIT).join( votes, votes.c.comment_id == Comment.id, isouter=True @@ -396,7 +293,10 @@ def edit_post(pid, v): if p.author_id != v.id and not (v.admin_level > 1 and v.admin_level > 2): abort(403) title = guarded_value("title", 1, MAX_TITLE_LENGTH) + title = sanitize_raw(title, allow_newlines=False, length_limit=MAX_TITLE_LENGTH) + body = guarded_value("body", 0, MAX_BODY_LENGTH) + body = sanitize_raw(body, allow_newlines=True, length_limit=MAX_BODY_LENGTH) if title != p.title: p.title = title @@ -414,22 +314,7 @@ def edit_post(pid, v): body += f"\n\n![]({url})" else: body += f'\n\n{url}' - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - if app.config['MULTIMEDIA_EMBEDDING_ENABLED']: - body += f"\n\n![]({url})" - else: - body += f'\n\n{url}' - else: abort(400, "Image/Video files only") + else: abort(400, "Image files only") body_html = sanitize(body, edit=True) @@ -663,11 +548,15 @@ def submit_post(v): if request.headers.get("Authorization") or request.headers.get("xhr"): abort(400, error) return render_template("submit.html", v=v, error=error, title=title, url=url, body=body), 400 - title = guarded_value("title", 1, MAX_TITLE_LENGTH) - url = guarded_value("url", 0, MAX_URL_LENGTH) - body = guarded_value("body", 0, MAX_BODY_LENGTH) - if v.is_suspended: return error("You can't perform this action while banned.") + + title = guarded_value("title", 1, MAX_TITLE_LENGTH) + title = sanitize_raw(title, allow_newlines=False, length_limit=MAX_TITLE_LENGTH) + + url = guarded_value("url", 0, MAX_URL_LENGTH) + + body = guarded_value("body", 0, MAX_BODY_LENGTH) + body = sanitize_raw(body, allow_newlines=True, length_limit=MAX_BODY_LENGTH) title_html = filter_emojis_only(title, graceful=True) @@ -819,23 +708,8 @@ def submit_post(v): body += f"\n\n![]({image})" else: body += f'\n\n{image}' - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: return error("Video upload timed out, please try again!") - try: url = req['link'] - except: - err = req['error'] - if err == 'File exceeds max duration': err += ' (60 seconds)' - return error(err) - if url.endswith('.'): url += 'mp4' - if app.config['MULTIMEDIA_EMBEDDING_ENABLED']: - body += f"\n\n![]({url})" - else: - body += f'\n\n{url}' else: - return error("Image/Video files only.") + return error("Image files only") body_html = sanitize(body) @@ -888,21 +762,9 @@ def submit_post(v): name2 = name.replace('.webp', 'r.webp') copyfile(name, name2) - post.thumburl = process_image(name2, resize=100) - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: return error("Video upload timed out, please try again!") - try: url = req['link'] - except: - err = req['error'] - if err == 'File exceeds max duration': err += ' (60 seconds)' - return error(err) - if url.endswith('.'): url += 'mp4' - post.url = url + post.thumburl = process_image(name2, resize=100) else: - return error("Image/Video files only.") + return error("Image files only") if not post.thumburl and post.url: gevent.spawn(thumbnail_thread, post.id) diff --git a/files/routes/settings.py b/files/routes/settings.py index 9acb82fe8..b82158b61 100644 --- a/files/routes/settings.py +++ b/files/routes/settings.py @@ -1,10 +1,9 @@ -from __future__ import unicode_literals from files.helpers.alerts import * +from files.helpers.media import process_image from files.helpers.sanitize import * from files.helpers.const import * from files.mail import * from files.__main__ import app, cache, limiter -import youtube_dl from .front import frontlist import os from files.helpers.sanitize import filter_emojis_only @@ -173,21 +172,9 @@ def settings_profile_post(v): file.save(name) url = process_image(name) bio += f"\n\n![]({url})" - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - bio += f"\n\n{url}" else: - if request.headers.get("Authorization") or request.headers.get("xhr"): abort(400, "Image/Video files only") - return render_template("settings_profile.html", v=v, error="Image/Video files only."), 400 + if request.headers.get("Authorization") or request.headers.get("xhr"): abort(400, "Image files only") + return render_template("settings_profile.html", v=v, error="Image files only"), 400 bio_html = sanitize(bio) @@ -217,14 +204,14 @@ def settings_profile_post(v): defaultsortingcomments = request.values.get("defaultsortingcomments") if defaultsortingcomments: - if defaultsortingcomments in {"new", "old", "controversial", "top", "bottom"}: + if defaultsortingcomments in SORTS_COMMENTS: v.defaultsortingcomments = defaultsortingcomments updated = True else: abort(400) defaultsorting = request.values.get("defaultsorting") if defaultsorting: - if defaultsorting in {"hot", "bump", "new", "old", "comments", "controversial", "top", "bottom"}: + if defaultsorting in SORTS_POSTS: v.defaultsorting = defaultsorting updated = True else: abort(400) @@ -549,7 +536,6 @@ def settings_profilecss(v): @limiter.limit("1/second;10/day") @auth_required def settings_block_user(v): - user = get_user(request.values.get("username"), graceful=True) if not user: abort(404, "That user doesn't exist.") @@ -567,11 +553,7 @@ def settings_block_user(v): target_id=user.id, ) g.db.add(new_block) - - send_notification(user.id, f"@{v.username} has blocked you!") - cache.delete_memoized(frontlist) - g.db.commit() return {"message": f"@{user.username} blocked."} @@ -581,19 +563,11 @@ def settings_block_user(v): @limiter.limit("1/second;30/minute;200/hour;1000/day") @auth_required def settings_unblock_user(v): - user = get_user(request.values.get("username")) - x = v.is_blocking(user) - if not x: abort(409) - g.db.delete(x) - - send_notification(user.id, f"@{v.username} has unblocked you!") - cache.delete_memoized(frontlist) - g.db.commit() return {"message": f"@{user.username} unblocked."} @@ -647,85 +621,6 @@ def settings_name_change(v): return redirect("/settings/profile") -@app.post("/settings/song_change") -@limiter.limit("2/second;10/day") -@auth_required -def settings_song_change(v): - song=request.values.get("song").strip() - - if song == "" and v.song: - if path.isfile(f"/songs/{v.song}.mp3") and g.db.query(User.id).filter_by(song=v.song).count() == 1: - os.remove(f"/songs/{v.song}.mp3") - v.song = None - g.db.add(v) - g.db.commit() - return redirect("/settings/profile") - - song = song.replace("https://music.youtube.com", "https://youtube.com") - if song.startswith(("https://www.youtube.com/watch?v=", "https://youtube.com/watch?v=", "https://m.youtube.com/watch?v=")): - id = song.split("v=")[1] - elif song.startswith("https://youtu.be/"): - id = song.split("https://youtu.be/")[1] - else: - return render_template("settings_profile.html", v=v, error="Not a youtube link.") - - if "?" in id: id = id.split("?")[0] - if "&" in id: id = id.split("&")[0] - - if path.isfile(f'/songs/{id}.mp3'): - v.song = id - g.db.add(v) - g.db.commit() - return redirect("/settings/profile") - - - req = requests.get(f"https://www.googleapis.com/youtube/v3/videos?id={id}&key={YOUTUBE_KEY}&part=contentDetails", timeout=5).json() - duration = req['items'][0]['contentDetails']['duration'] - if duration == 'P0D': - return render_template("settings_profile.html", v=v, error="Can't use a live youtube video!") - - if "H" in duration: - return render_template("settings_profile.html", v=v, error="Duration of the video must not exceed 15 minutes.") - - if "M" in duration: - duration = int(duration.split("PT")[1].split("M")[0]) - if duration > 15: - return render_template("settings_profile.html", v=v, error="Duration of the video must not exceed 15 minutes.") - - - if v.song and path.isfile(f"/songs/{v.song}.mp3") and g.db.query(User.id).filter_by(song=v.song).count() == 1: - os.remove(f"/songs/{v.song}.mp3") - - ydl_opts = { - 'outtmpl': '/songs/%(title)s.%(ext)s', - 'format': 'bestaudio/best', - 'postprocessors': [{ - 'key': 'FFmpegExtractAudio', - 'preferredcodec': 'mp3', - 'preferredquality': '192', - }], - } - - with youtube_dl.YoutubeDL(ydl_opts) as ydl: - try: ydl.download([f"https://youtube.com/watch?v={id}"]) - except Exception as e: - print(e) - return render_template("settings_profile.html", - v=v, - error="Age-restricted videos aren't allowed.") - - files = os.listdir("/songs/") - paths = [path.join("/songs/", basename) for basename in files] - songfile = max(paths, key=path.getctime) - os.rename(songfile, f"/songs/{id}.mp3") - - v.song = id - g.db.add(v) - - g.db.commit() - - return redirect("/settings/profile") - @app.post("/settings/title_change") @limiter.limit("1/second;30/minute;200/hour;1000/day") @auth_required diff --git a/files/routes/static.py b/files/routes/static.py index b362e6947..ab1f0734d 100644 --- a/files/routes/static.py +++ b/files/routes/static.py @@ -1,7 +1,9 @@ +from files.helpers.media import process_image from files.mail import * from files.__main__ import app, limiter, mail from files.helpers.alerts import * from files.helpers.const import * +from files.helpers.captcha import validate_captcha from files.classes.award import AWARDS from sqlalchemy import func from os import path @@ -108,15 +110,13 @@ def chart(): @app.get("/weekly_chart") -@auth_desired -def weekly_chart(v): +def weekly_chart(): file = cached_chart(kind="weekly", site=SITE) f = send_file(file) return f @app.get("/daily_chart") -@auth_desired -def daily_chart(v): +def daily_chart(): file = cached_chart(kind="daily", site=SITE) f = send_file(file) return f @@ -280,13 +280,17 @@ def api(v): @app.get("/media") @auth_desired def contact(v): - - return render_template("contact.html", v=v) + return render_template("contact.html", v=v, + hcaptcha=app.config.get("HCAPTCHA_SITEKEY", "")) @app.post("/send_admin") @limiter.limit("1/second;2/minute;6/hour;10/day") @auth_desired -def submit_contact(v): +def submit_contact(v: Optional[User]): + if not v and not validate_captcha(app.config.get("HCAPTCHA_SECRET", ""), + app.config.get("HCAPTCHA_SITEKEY", ""), + request.values.get("h-captcha-response", "")): + abort(403, "CAPTCHA provided was not correct. Please try it again") body = request.values.get("message") email = request.values.get("email") if not body: abort(400) @@ -306,25 +310,13 @@ def submit_contact(v): file.save(name) url = process_image(name) html += f'' - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - html += f"

{url}

" - else: abort(400, "Image/Video files only") + else: abort(400, "Image files only") new_comment = Comment(author_id=v.id if v else NOTIFICATIONS_ID, parent_submission=None, level=1, body_html=html, - sentto=2 + sentto=MODMAIL_ID, ) g.db.add(new_comment) g.db.flush() diff --git a/files/routes/users.py b/files/routes/users.py index cf9b671e3..fd87139c9 100644 --- a/files/routes/users.py +++ b/files/routes/users.py @@ -2,8 +2,11 @@ import qrcode import io import time import math + +from files.classes.leaderboard import SimpleLeaderboard, BadgeMarseyLeaderboard, UserBlockLeaderboard, LeaderboardMeta from files.classes.views import ViewerRelationship from files.helpers.alerts import * +from files.helpers.media import process_image from files.helpers.sanitize import * from files.helpers.strings import sql_ilike_clean from files.helpers.const import * @@ -11,69 +14,14 @@ from files.helpers.assetcache import assetcache_path from files.helpers.contentsorting import apply_time_filter, sort_objects from files.mail import * from flask import * -from files.__main__ import app, limiter, db_session -from pusher_push_notifications import PushNotifications +from files.__main__ import app, limiter from collections import Counter import gevent -from sys import stdout -if PUSHER_ID != 'blahblahblah': - beams_client = PushNotifications(instance_id=PUSHER_ID, secret_key=PUSHER_KEY) - -def pusher_thread2(interests, notifbody, username): - beams_client.publish_to_interests( - interests=[interests], - publish_body={ - 'web': { - 'notification': { - 'title': f'New message from @{username}', - 'body': notifbody, - 'deep_link': f'{SITE_FULL}/notifications?messages=true', - 'icon': SITE_FULL + assetcache_path(f'images/{SITE_ID}/icon.webp'), - } - }, - 'fcm': { - 'notification': { - 'title': f'New message from @{username}', - 'body': notifbody, - }, - 'data': { - 'url': '/notifications?messages=true', - } - } - }, - ) - stdout.flush() - -def leaderboard_thread(): - global users9, users9_25, users13, users13_25 - - db = db_session() - - votes1 = db.query(Submission.author_id, func.count(Submission.author_id)).join(Vote, Vote.submission_id==Submission.id).filter(Vote.vote_type==-1).group_by(Submission.author_id).order_by(func.count(Submission.author_id).desc()).all() - votes2 = db.query(Comment.author_id, func.count(Comment.author_id)).join(CommentVote, CommentVote.comment_id==Comment.id).filter(CommentVote.vote_type==-1).group_by(Comment.author_id).order_by(func.count(Comment.author_id).desc()).all() - votes3 = Counter(dict(votes1)) + Counter(dict(votes2)) - users8 = db.query(User).filter(User.id.in_(votes3.keys())).all() - users9 = [] - for user in users8: users9.append((user, votes3[user.id])) - users9 = sorted(users9, key=lambda x: x[1], reverse=True) - users9_25 = users9[:25] - - votes1 = db.query(Vote.user_id, func.count(Vote.user_id)).filter(Vote.vote_type==1).group_by(Vote.user_id).order_by(func.count(Vote.user_id).desc()).all() - votes2 = db.query(CommentVote.user_id, func.count(CommentVote.user_id)).filter(CommentVote.vote_type==1).group_by(CommentVote.user_id).order_by(func.count(CommentVote.user_id).desc()).all() - votes3 = Counter(dict(votes1)) + Counter(dict(votes2)) - users14 = db.query(User).filter(User.id.in_(votes3.keys())).all() - users13 = [] - for user in users14: - users13.append((user, votes3[user.id]-user.post_count-user.comment_count)) - users13 = sorted(users13, key=lambda x: x[1], reverse=True) - users13_25 = users13[:25] - - db.close() - stdout.flush() - -if app.config["ENABLE_SERVICES"]: - gevent.spawn(leaderboard_thread()) +# warning: do not move currently. these have import-time side effects but +# until this is refactored to be not completely awful, there's not really +# a better option. +from files.helpers.services import * @app.get("/@/upvoters//posts") @admin_level_required(3) @@ -411,73 +359,26 @@ def transfer_bux(v, username): @app.get("/leaderboard") @admin_level_required(2) -def leaderboard(v): +def leaderboard(v:User): + users:Query = g.db.query(User) + if not v.can_see_shadowbanned: + users = users.filter(User.shadowbanned == None) - users = g.db.query(User) + coins = SimpleLeaderboard(v, LeaderboardMeta("Coins", "coins", "coins", "Coins", None), g.db, users, User.coins) + subscribers = SimpleLeaderboard(v, LeaderboardMeta("Followers", "followers", "followers", "Followers", "followers"), g.db, users, User.stored_subscriber_count) + posts = SimpleLeaderboard(v, LeaderboardMeta("Posts", "post count", "posts", "Posts", ""), g.db, users, User.post_count) + comments = SimpleLeaderboard(v, LeaderboardMeta("Comments", "comment count", "comments", "Comments", "comments"), g.db, users, User.comment_count) + received_awards = SimpleLeaderboard(v, LeaderboardMeta("Awards", "received awards", "awards", "Awards", None), g.db, users, User.received_award_count) + coins_spent = SimpleLeaderboard(v, LeaderboardMeta("Spent in shop", "coins spent in shop", "spent", "Coins", None), g.db, users, User.coins_spent) + truescore = SimpleLeaderboard(v, LeaderboardMeta("Truescore", "truescore", "truescore", "Truescore", None), g.db, users, User.truecoins) + badges = BadgeMarseyLeaderboard(v, LeaderboardMeta("Badges", "badges", "badges", "Badges", None), g.db, Badge.user_id) + blocks = UserBlockLeaderboard(v, LeaderboardMeta("Blocked", "most blocked", "blocked", "Blocked By", "blockers"), g.db, UserBlock.target_id) - users1 = users.order_by(User.coins.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.coins.desc()).label("rank")).subquery() - pos1 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] + # note: lb_downvotes_received and lb_upvotes_given are global variables + # that are populated by leaderboard_thread() in files.helpers.services + leaderboards = [coins, coins_spent, truescore, subscribers, posts, comments, received_awards, badges, blocks, lb_downvotes_received, lb_upvotes_given] - users2 = users.order_by(User.stored_subscriber_count.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.stored_subscriber_count.desc()).label("rank")).subquery() - pos2 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - users3 = users.order_by(User.post_count.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.post_count.desc()).label("rank")).subquery() - pos3 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - users4 = users.order_by(User.comment_count.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.comment_count.desc()).label("rank")).subquery() - pos4 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - users5 = users.order_by(User.received_award_count.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.received_award_count.desc()).label("rank")).subquery() - pos5 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - users6 = None - pos6 = None - - users7 = users.order_by(User.coins_spent.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.coins_spent.desc()).label("rank")).subquery() - pos7 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - try: - pos9 = [x[0].id for x in users9].index(v.id) - pos9 = (pos9+1, users9[pos9][1]) - except: pos9 = (len(users9)+1, 0) - - users10 = users.order_by(User.truecoins.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.truecoins.desc()).label("rank")).subquery() - pos10 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - sq = g.db.query(Badge.user_id, func.count(Badge.user_id).label("count"), func.rank().over(order_by=func.count(Badge.user_id).desc()).label("rank")).group_by(Badge.user_id).subquery() - users11 = g.db.query(User, sq.c.count).join(sq, User.id==sq.c.user_id).order_by(sq.c.count.desc()) - pos11 = g.db.query(User.id, sq.c.rank, sq.c.count).join(sq, User.id==sq.c.user_id).filter(User.id == v.id).one_or_none() - if pos11: pos11 = (pos11[1],pos11[2]) - else: pos11 = (users11.count()+1, 0) - users11 = users11.limit(25).all() - - if pos11[1] < 25 and v not in (x[0] for x in users11): - pos11 = (26, pos11[1]) - - users12 = None - pos12 = None - - try: - pos13 = [x[0].id for x in users13].index(v.id) - pos13 = (pos13+1, users13[pos13][1]) - except: pos13 = (len(users13)+1, 0) - - users14 = users.order_by(User.winnings.desc()).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.winnings.desc()).label("rank")).subquery() - pos14 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - users15 = users.order_by(User.winnings).limit(25).all() - sq = g.db.query(User.id, func.rank().over(order_by=User.winnings).label("rank")).subquery() - pos15 = g.db.query(sq.c.id, sq.c.rank).filter(sq.c.id == v.id).limit(1).one()[1] - - return render_template("leaderboard.html", v=v, users1=users1, pos1=pos1, users2=users2, pos2=pos2, users3=users3, pos3=pos3, users4=users4, pos4=pos4, users5=users5, pos5=pos5, users6=users6, pos6=pos6, users7=users7, pos7=pos7, users9=users9_25, pos9=pos9, users10=users10, pos10=pos10, users11=users11, pos11=pos11, users12=users12, pos12=pos12, users13=users13_25, pos13=pos13, users14=users14, pos14=pos14, users15=users15, pos15=pos15) + return render_template("leaderboard.html", v=v, leaderboards=leaderboards) @app.get("/@/css") def get_css(username): @@ -495,20 +396,6 @@ def get_profilecss(username): resp.headers.add("Content-Type", "text/css") return resp -@app.get("/@/song") -def usersong(username): - user = get_user(username) - if user.song: return redirect(f"/song/{user.song}.mp3") - else: abort(404) - -@app.get("/song/") -@app.get("/static/song/") -def song(song): - resp = make_response(send_from_directory('/songs', song)) - resp.headers.remove("Cache-Control") - resp.headers.add("Cache-Control", "public, max-age=3153600") - return resp - @app.post("/subscribe/") @limiter.limit("1/second;30/minute;200/hour;1000/day") @auth_required @@ -529,8 +416,7 @@ def unsubscribe(v, post_id): return {"message": "Post unsubscribed!"} @app.get("/report_bugs") -@auth_required -def reportbugs(v): +def reportbugs(): return redirect(f'/post/{BUG_THREAD}') @app.post("/@/message") @@ -542,6 +428,10 @@ def message2(v, username): "contact modmail if you think this decision was incorrect.") user = get_user(username, v=v, include_blocks=True) + + if user.id == MODMAIL_ID: + abort(403, "Please use modmail to contact the admins") + if hasattr(user, 'is_blocking') and user.is_blocking: abort(403, "You're blocking this user.") if v.admin_level <= 1 and hasattr(user, 'is_blocked') and user.is_blocked: @@ -550,7 +440,6 @@ def message2(v, username): message = request.values.get("message", "").strip()[:10000].strip() if not message: abort(400, "Message is empty!") - body_html = sanitize(message) existing = g.db.query(Comment.id).filter(Comment.author_id == v.id, @@ -567,7 +456,6 @@ def message2(v, username): body_html=body_html ) g.db.add(c) - g.db.flush() c.top_comment_id = c.id @@ -602,31 +490,19 @@ def messagereply(v): parent = get_comment(id, v=v) user_id = parent.author.id - if parent.sentto == 2: user_id = None + if parent.sentto == MODMAIL_ID: user_id = None elif v.id == user_id: user_id = parent.sentto body_html = sanitize(message) - if parent.sentto == 2 and request.files.get("file") and request.headers.get("cf-ipcountry") != "T1": + if parent.sentto == MODMAIL_ID and request.files.get("file") and request.headers.get("cf-ipcountry") != "T1": file=request.files["file"] if file.content_type.startswith('image/'): name = f'/images/{time.time()}'.replace('.','') + '.webp' file.save(name) url = process_image(name) body_html += f'' - elif file.content_type.startswith('video/'): - file.save("video.mp4") - with open("video.mp4", 'rb') as f: - try: req = requests.request("POST", "https://api.imgur.com/3/upload", headers={'Authorization': f'Client-ID {IMGUR_KEY}'}, files=[('video', f)], timeout=5).json()['data'] - except requests.Timeout: abort(500, "Video upload timed out, please try again!") - try: url = req['link'] - except: - error = req['error'] - if error == 'File exceeds max duration': error += ' (60 seconds)' - abort(400, error) - if url.endswith('.'): url += 'mp4' - body_html += f"

{url}

" - else: abort(400, "Image/Video files only") + else: abort(400, "Image files only") c = Comment(author_id=v.id, @@ -678,7 +554,7 @@ def messagereply(v): ) - if c.top_comment.sentto == 2: + if c.top_comment.sentto == MODMAIL_ID: admins = g.db.query(User).filter(User.admin_level > 2, User.id != v.id).all() for admin in admins: notif = Notification(comment_id=c.id, user_id=admin.id) @@ -737,15 +613,13 @@ def api_is_available(name): else: return {name: True} -@app.get("/id/") -@auth_desired -def user_id(v, id): +@app.get("/id/") +def user_id(id:int): user = get_account(id) return redirect(user.url) @app.get("/u/") -@auth_desired -def redditor_moment_redirect(v, username): +def redditor_moment_redirect(username:str): return redirect(f"/@{username}") @app.get("/@/followers") @@ -1002,7 +876,6 @@ import re @app.get("/uid//pic") @app.get("/uid//pic/profile") @limiter.exempt -@auth_desired def user_profile_uid(v, id): try: id = int(id) except: @@ -1033,8 +906,7 @@ def user_profile_uid(v, id): @app.get("/@/pic") @limiter.exempt -@auth_required -def user_profile_name(v, username): +def user_profile_name(username:str): name = f"/@{username}/pic" path = cache.get(name) diff --git a/files/routes/votes.py b/files/routes/votes.py index 9328f57a8..a0ab1b62c 100644 --- a/files/routes/votes.py +++ b/files/routes/votes.py @@ -21,8 +21,6 @@ def admin_vote_info_get(v): if thing.ghost and v.id != OWNER_ID: abort(403) - if not thing.author: - print(thing.id, flush=True) if isinstance(thing, Submission): if thing.author.shadowbanned and not (v and v.admin_level): thing_id = g.db.query(Submission.id).filter_by(upvotes=thing.upvotes, downvotes=thing.downvotes).order_by(Submission.id).first()[0] diff --git a/files/templates/admin/shadowbanned_tooltip.html b/files/templates/admin/shadowbanned_tooltip.html new file mode 100644 index 000000000..2c795543c --- /dev/null +++ b/files/templates/admin/shadowbanned_tooltip.html @@ -0,0 +1 @@ +{% if v and v.admin_level >= PERMS['USER_SHADOWBAN'] and user.shadowbanned %}{% endif %} diff --git a/files/templates/award_modal.html b/files/templates/award_modal.html index 9e3c2c8d9..2b5e29702 100644 --- a/files/templates/award_modal.html +++ b/files/templates/award_modal.html @@ -44,4 +44,6 @@ +{% if FEATURES['AWARDS'] %} +{% endif %} diff --git a/files/templates/changelog.html b/files/templates/changelog.html index 3da3f88cc..0be252871 100644 --- a/files/templates/changelog.html +++ b/files/templates/changelog.html @@ -1,4 +1,5 @@ {% extends "settings2.html" %} +{%- import 'component/sorting_time.html' as sorting_time -%} {% block pagetitle %}Changelog{% endblock %} @@ -35,27 +36,7 @@
‎
- + {{sorting_time.sort_dropdown(sort, t, SORTS_POSTS)}} {% endblock %} @@ -72,13 +53,9 @@ {% endif %}
-
-
- {% include "submission_listing.html" %} -
diff --git a/files/templates/comments.html b/files/templates/comments.html index bfb02439b..eb3dd4445 100644 --- a/files/templates/comments.html +++ b/files/templates/comments.html @@ -47,7 +47,7 @@ {% macro single_comment(c, level) %} -{% if c.should_hide_score %} +{% if should_hide_score or c.should_hide_score %} {% set ups="" %} {% set downs="" %} {% set score="" %} @@ -72,20 +72,14 @@
- -
- - - -
- +
{% if render_replies %} - {% if level<9 %} + {% if level <= RENDER_DEPTH_LIMIT - 1 %}
{% set standalone=False %} {% for reply in replies %} @@ -143,7 +137,7 @@ {% elif c.author_id==NOTIFICATIONS_ID or c.author_id==AUTOJANNY_ID %} Notification {% else %} - {% if c.sentto == 2 %} + {% if c.sentto == MODMAIL_ID %} Sent to admins {% else %} Sent to @{{c.senttouser.username}} @@ -153,7 +147,7 @@
{% endif %} -{% if c.parent_comment and c.parent_comment.sentto %} +{% if not standalone and c.parent_comment and c.parent_comment.sentto %} {% set isreply = True %} {% else %} {% set isreply = False %} @@ -171,25 +165,27 @@ {% if c.ghost %} 👻 {% else %} - {% if c.author.verified %} {% endif %} - {% if not c.author %} - {{c.print()}} + {% if not should_hide_username %} + {{c.author_name}} {% endif %} - {{c.author_name}} {% if v and v.admin_level > 1 %} U {% endif %} - {% if c.author.customtitle %}  {{c.author.customtitle | safe}}{% endif %} + {% if c.author.customtitle and not should_hide_username -%} +   {{c.author.customtitle | safe}} + {%- endif %} {% endif %} - {% for a in c.awards|reverse %} - - {% endfor %} + {% if FEATURES['AWARDS'] %} + {% for a in c.awards|reverse %} + + {% endfor %} + {% endif %} {% if c.bannedfor %} @@ -221,7 +217,7 @@
-
+
{% if v and c.filter_state == 'reported' and v.can_manage_reports() %} @@ -487,7 +483,7 @@  
Comment @@ -500,7 +496,7 @@ {% if render_replies %} - {% if level<9 or request.path == '/notifications' %} + {% if level <= RENDER_DEPTH_LIMIT - 1 or request.path == '/notifications' %}
{% for reply in replies %} {{single_comment(reply, level=level+1)}} @@ -522,10 +518,10 @@
- {% if c.sentto == 2 %} + {% if c.sentto == MODMAIL_ID %} {% endif %}
@@ -748,7 +744,9 @@ - + {% if FEATURES['AWARDS'] %} + + {% endif %} {% endif %} diff --git a/files/templates/component/sorting_time.html b/files/templates/component/sorting_time.html new file mode 100644 index 000000000..e797be871 --- /dev/null +++ b/files/templates/component/sorting_time.html @@ -0,0 +1,14 @@ +{%- macro sort_dropdown(sort, t, all_sorts, extra_query='') -%} + +{%- endmacro -%} diff --git a/files/templates/contact.html b/files/templates/contact.html index 86541913a..e149b61ef 100644 --- a/files/templates/contact.html +++ b/files/templates/contact.html @@ -1,12 +1,8 @@ {% extends "default.html" %} - {% block title %} {{SITE_TITLE}} - Contact - {% endblock %} - {% block content %} - {% if msg %} {% endif %} - +

Contact {{SITE_TITLE}} Admins

Use this form to contact {{SITE_TITLE}} Admins.

@@ -32,20 +28,18 @@ + {% if not v and hcaptcha %} +
+ {% endif %} - -
-
-
-	
- -

If you can see this line, we haven't been contacted by any law enforcement or governmental organizations in 2022 yet.

- -
-
-
-	
+
+
+

If you can see this line, we haven't been contacted by any law enforcement or governmental organizations in 2022 yet.

+
+ {% if hcaptcha %} + + {% endif %} {% endblock %} diff --git a/files/templates/home.html b/files/templates/home.html index 1f59182c1..cfd1dd846 100644 --- a/files/templates/home.html +++ b/files/templates/home.html @@ -1,5 +1,5 @@ {% extends "default.html" %} - +{%- import 'component/sorting_time.html' as sorting_time -%} {% block desktopBanner %} {% if v and environ.get("FP") %} @@ -73,30 +73,8 @@ {% if t != "all" %}All{% endif %}
- - + {% set ccmode_text = 'ccmode=' ~ ccmode %} + {{sorting_time.sort_dropdown(sort, t, SORTS_POSTS, ccmode_text)}}
{% endblock %}
@@ -104,21 +82,14 @@ {% endblock %} - {% block content %} -
-
-
- {% include "submission_listing.html" %} -
- {% endblock %} {% block pagenav %} diff --git a/files/templates/home_comments.html b/files/templates/home_comments.html index 2237caf0d..c79f5a487 100644 --- a/files/templates/home_comments.html +++ b/files/templates/home_comments.html @@ -1,4 +1,5 @@ {% extends "default.html" %} +{%- import 'component/sorting_time.html' as sorting_time -%} {% block sortnav %}{% endblock %} @@ -30,39 +31,17 @@
‎
- + {{sorting_time.sort_dropdown(sort, t, SORTS_COMMENTS)}}
-
-
- {% include "comments.html" %} -
- - {% endblock %} {% block pagenav %} diff --git a/files/templates/leaderboard.html b/files/templates/leaderboard.html index 549b3f5a6..e017131c9 100644 --- a/files/templates/leaderboard.html +++ b/files/templates/leaderboard.html @@ -1,484 +1,62 @@ {% extends "settings2.html" %} - {% block pagetitle %}Leaderboard{% endblock %} - {% block content %}

-
Top 25 by coins
-

-
- - - - - - - -{% for user in users1 %} - - - - - -{% endfor %} -{% if pos1 > 25 %} - - - - - -{% endif %} -
#NameCoins
{{loop.index}}{{user.username}}{{user.coins}}
{{pos1}}{{v.username}}{{v.coins}}
- - -
-
-
-
-
Top 25 by coins spent in shop
-
-
-
-
-
- - - - - - - - -{% for user in users7 %} - - - - - -{% endfor %} -{% if pos7 > 25 %} - - - - - -{% endif %} -
#NameCoins
{{loop.index}}{{user.username}}{{user.coins_spent}}
{{pos7}}{{v.username}}{{v.coins_spent}}
- - -
-
-
-
-
Top 25 by truescore
-
-
-
-
-
- - - - - - - - - {% for user in users10 %} - - - - - - {% endfor %} - {% if pos10 > 25 %} - - - - - - {% endif %} - -
#NameTruescore
{{loop.index}}{{user.username}}{{user.truecoins}}
{{pos10}}{{v.username}}{{v.truecoins}}
- -
-
-
-
-
Top 25 by followers
-
-
-
-
-
- - - - - - - -{% for user in users2 %} - - - - - -{% endfor %} -{% if pos2 > 25 %} - - - - - -{% endif %} -
#NameFollowers
{{loop.index}}{{user.username}}{{user.stored_subscriber_count}}
{{pos2}}{{v.username}}{{v.stored_subscriber_count}}
-
-
-
-
-
Top 25 by post count
-
-
-
-
-
- - - - - - - -{% for user in users3 %} - - - - - -{% endfor %} -{% if pos3 > 25 %} - - - - - -{% endif %} -
#NamePosts
{{loop.index}}{{user.username}}{{user.post_count}}
{{pos3}}{{v.username}}{{v.post_count}}
-
-
-
-
-
Top 25 by comment count
-
-
-
-
-
- - - - - - - -{% for user in users4 %} - - - - - -{% endfor %} -{% if pos4 > 25 %} - - - - - -{% endif %} -
#NameComments
{{loop.index}}{{user.username}}{{user.comment_count}}
{{pos4}}{{v.username}}{{v.comment_count}}
- - -
-
-
-
-
Top 25 by received awards
-
-
-
-
-
- - - - - - - -{% for user in users5 %} - - - - - -{% endfor %} -{% if pos5 > 25 %} - - - - - -{% endif %} -
#NameAwards
{{loop.index}}{{user.username}}{{user.received_award_count}}
{{pos5}}{{v.username}}{{v.received_award_count}}
- - -
-
-
-
-
Top 25 by received downvotes
-
-
-
-
- -
- - - - - - - - - {% for user in users9 %} - - - - - - {% endfor %} - {% if pos9 and (pos9[0] > 25 or not pos9[1]) %} - - - - - - {% endif %} - -
#NameDownvotes
{{loop.index}}{{user[0].username}}{{user[1]}}
{{pos9[0]}}{{v.username}}{{pos9[1]}}
- - -
-
-
-
-
Top 25 by badges
-
-
-
-
- -
- - - - - - - - - {% for user in users11 %} - - - - - - {% endfor %} - {% if pos11 and (pos11[0] > 25 or not pos11[1]) %} - - - - - - {% endif %} - -
#NameBadges
{{loop.index}}{{user[0].username}}{{user[1]}}
{{pos11[0]}}{{v.username}}{{pos11[1]}}
- - - -{% if users6 %} -
-
-
-	
-
Top 25 by based count
-
-
-
-	
-
- - - - - - - - {% for user in users6 %} - - - - - - {% endfor %} - {% if pos6 > 25 %} - - - - - - {% endif %} -
#NameBased count
{{loop.index}}{{user.username}}{{user.basedcount}}
{{pos6}}{{v.username}}{{v.basedcount}}
-{% endif %} - -{% if users12 %} -
-
-
-	
-
Top 25 by marseys made
-
-
-
-	
- -
- - - - - - - - - {% for user in users12 %} - - - - - - {% endfor %} - {% if pos12 and (pos12[0] > 25 or not pos12[1]) %} - - - - - +
+ {% for lb in leaderboards %} + {% if lb %} + {{lb.meta.header_name}}{% if not loop.last %} •{% endif %} {% endif %} -
-
#NameMarseys
{{loop.index}}{{user[0].username}}{{user[1]}}
{{pos12[0]}}{{v.username}}{{pos12[1]}}
-{% endif %} + {% endfor %} +
-{% if users13 %} -
-
-
-	
-
Top 25 by upvotes given
-
-
-
-	
- -
- - - - - - - - - {% for user in users13 %} - - - - - - {% endfor %} - {% if pos13 and (pos13[0] > 25 or not pos13[1]) %} - - - - - +{% macro format_user_in_table(user, style, position_no, value, user_relative_url) %} + {% set value = value | int %} + + + + {% if user_relative_url is not none %} + + {% else %} + {% endif %} - -
#NameUpvotes
{{loop.index}}{{user[0].username}}{{user[1]}}
{{pos13[0]}}{{v.username}}{{pos13[1]}}
{{position_no}}{% include "user_in_table.html" %}{{"{:,}".format(value)}}{{"{:,}".format(value)}}
-{% endif %} + +{% endmacro %} -
Top 25 by winnings
-

-
- - - - - - - -{% for user in users14 %} - - - - - -{% endfor %} -{% if pos14 > 25 %} - - - - - -{% endif %} +{% macro leaderboard_table(lb) %} +
Top {{lb.limit}} {% if lb.meta.table_header_name != 'most blocked' %}by{% endif %} {{lb.meta.table_header_name}}
+
+
#NameWinnings
{{loop.index}}{{user.username}}{{user.winnings}}
{{pos14}}{{v.username}}{{v.winnings}}
+ + + + + + + + + {% for user in lb.all_users %} + {% set user2 = lb.user_func(user) %} + {% if v.id == user2.id %} + {% set style="class=\"self\"" %} + {% endif %} + {{format_user_in_table(user2, style, loop.index, lb.value_func(user), lb.meta.user_relative_url)}} + {% endfor %} + {% if lb.v_position and not lb.v_appears_in_ranking %} + {{format_user_in_table(v, "style=\"border-top:2px solid var(--primary)\"", lb.v_position, lb.v_value, lb.meta.user_relative_url)}} + {% endif %} +
#Name{{lb.meta.table_column_name}}
+
+{% endmacro %} - -
-
-
-
-
Bottom 25 by winnings
-

-
- - - - - - - -{% for user in users15 %} - - - - - +{% for lb in leaderboards %} + {% if lb %} + {{leaderboard_table(lb)}} + {% endif %} {% endfor %} -{% if pos15 > 25 %} - - - - - -{% endif %} -
#NameWinnings
{{loop.index}}{{user.username}}{{user.winnings}}
{{pos15}}{{v.username}}{{v.winnings}}
- - -
-
-
-
+ + + {% endblock %} diff --git a/files/templates/search.html b/files/templates/search.html index 2e232a0d0..d4d6a27b4 100644 --- a/files/templates/search.html +++ b/files/templates/search.html @@ -1,4 +1,5 @@ {% extends "home.html" %} +{%- import 'component/sorting_time.html' as sorting_time -%} {% block pagetype %}search{% endblock %} @@ -29,38 +30,15 @@ {% if t != "all" %}All{% endif %}
- - + {% set query_text = 'q=' ~ query | urlencode %} + {{sorting_time.sort_dropdown(sort, t, SORTS_POSTS, query_text)}}
{% endif %} {% endblock %} - {% block content %} -
-
-
-
  • @@ -73,91 +51,47 @@
    Showing {% block listinglength %}{{listing | length}}{% endblock %} of {{total}} result{{'s' if total != 1 else ''}} for

    {{query}}

    -
-
- - -{% if not '/users/' in request.path %} - -
- - - -
- {% endif %} - -
-
-
- -
-
-
- -
- -
- -
- - {% block listing_template %} - {% include "submission_listing.html" %} - {% endblock %} - -
-
-
- {% endblock %} - - {% block pagenav %} - - - {% endblock %} +
+
+
+
+
+
+ {% block listing_template %} + {% include "submission_listing.html" %} + {% endblock %} +
+
+
+{% endblock %} +{% block pagenav %} + +{% endblock %} diff --git a/files/templates/settings_filters.html b/files/templates/settings_filters.html index 477542a8a..af2b4d952 100644 --- a/files/templates/settings_filters.html +++ b/files/templates/settings_filters.html @@ -1,24 +1,15 @@ {% extends "settings.html" %} - {% block pagetitle %}Profile Settings - {{SITE_TITLE}}{% endblock %} - {% block content %} - -
-
-
-

Frontpage Size

-
-

Change how many posts appear on every page.

@@ -28,9 +19,7 @@ {% endfor %}
-
-
@@ -48,14 +37,12 @@

Change the default sorting for comments.

-
-
@@ -67,21 +54,17 @@

Change the default sorting for posts.

-
-
-
-

Change the default time filter for posts.

@@ -91,34 +74,24 @@ {% endfor %}
-
-
-

Tab Behaviour

-
-
-
-
- Enable if you would like to automatically open links to other pages in the site in new tabs. -
-
@@ -136,51 +109,34 @@
Enable if you would like to automatically open links to other sites in new tabs. -
-
- - -

Twitter Links

-
-
-
-
- Enable if you would like to automatically convert twitter.com links to nitter.net links. -
-
-
-

Reddit Links

-
-
-

Change the domain you would like to view reddit posts in.

@@ -190,28 +146,21 @@ {% endfor %}
-
-
-
-
- Enable if you would like to automatically sort reddit.com links by controversial. -
-
diff --git a/files/templates/settings_profile.html b/files/templates/settings_profile.html index 2a8b13cba..bfe98536d 100644 --- a/files/templates/settings_profile.html +++ b/files/templates/settings_profile.html @@ -384,7 +384,7 @@  

diff --git a/files/templates/submission.html b/files/templates/submission.html
index 736f29687..28290b84d 100644
--- a/files/templates/submission.html
+++ b/files/templates/submission.html
@@ -1,5 +1,5 @@
 {% extends "default.html" %}
-
+{%- import 'component/sorting_time.html' as sorting_time -%}
 
 {% if p.should_hide_score %}
 	{% set ups="" %}
@@ -137,7 +137,7 @@
 	
-
+
@@ -164,15 +164,9 @@ {% if v and p.filter_state == 'reported' and v.can_manage_reports() %} {{p.active_flags(v)}} Reports {% endif %} - - {% if not p.author %} - {{p.print()}} - {% endif %} - {% if p.ghost %} 👻 {% else %} - {% if p.author.verified %} {% endif %} @@ -233,7 +227,6 @@ {% endif %} {% endif %} - {% if p.embed_url %} {% if p.domain == "twitter.com" %} {{p.embed_url | safe}} @@ -246,8 +239,6 @@ {{p.embed_url | safe}} {% endif %} {% endif %} - -
{% if p.is_image %}
@@ -295,7 +286,7 @@ @@ -342,16 +333,11 @@ {% include 'post_actions.html' %}
-
-
- {% if v %} -
-
- +
{{score}}
@@ -364,16 +350,9 @@ {{score}}
- {% endif %} -
- - - -
-
{% if not p.is_image and not p.is_video %} @@ -387,10 +366,8 @@ {% if v and v.id != p.author_id and p.body %} @@ -445,27 +420,12 @@
- {% if v %} @@ -487,7 +447,7 @@  
Comment @@ -606,18 +566,6 @@ {% include "comments.html" %} {% endif %} -{% if p.award_count("shit") %} - - -{% endif %} - - -{% if p.award_count("fireflies") %} - - -{% endif %} - -
{{u.username}}
{% endif %} - - {% endblock %} {% block pagenav %} diff --git a/files/templates/userpage_comments.html b/files/templates/userpage_comments.html index 44c4f5a77..b8f4890bd 100644 --- a/files/templates/userpage_comments.html +++ b/files/templates/userpage_comments.html @@ -1,4 +1,5 @@ {% extends "userpage.html" %} +{%- import 'component/sorting_time.html' as sorting_time -%} {% block content %} @@ -52,23 +53,7 @@
‎
- + {{sorting_time.sort_dropdown(sort, t, SORTS_COMMENTS)}}
{% endif %} @@ -104,19 +89,10 @@ -{% if u.song %} - {% if v and v.id == u.id %} -
{{v.username}}
- {% else %} -
{{u.username}}
- {% endif %} -{% endif %} - {% if v %}
{% if v.patron or u.patron %}0{% else %}0.03{% endif %}
{{u.username}}
{% endif %} - {% endblock %} diff --git a/files/templates/userpage_private.html b/files/templates/userpage_private.html index 127daffbf..415a5d4ca 100644 --- a/files/templates/userpage_private.html +++ b/files/templates/userpage_private.html @@ -15,20 +15,9 @@ -{% if u.song %} - {% if v and v.id == u.id %} -
{{v.username}}
- {% else %} -
{{u.username}}
- {% endif %} -{% endif %} - {% endblock %} {% block pagenav %} -{% if u.song %} -
{{u.id}}
-{% endif %} {% if v %}
{% if v.patron or u.patron %}0{% else %}0.03{% endif %}
@@ -36,5 +25,4 @@
{{u.username}}
{% endif %} - {% endblock %} diff --git a/files/templates/volunteer_janitor.html b/files/templates/volunteer_janitor.html index 00cb72ddd..43bc6dbea 100644 --- a/files/templates/volunteer_janitor.html +++ b/files/templates/volunteer_janitor.html @@ -14,6 +14,8 @@
{% with comments=[c] %} + {% set should_hide_username = true %} + {% set should_hide_score = true %} {% include "comments.html" %} {% endwith %}
diff --git a/files/tests/test_basic.py b/files/tests/test_basic.py index a654fd0b6..8912bb828 100644 --- a/files/tests/test_basic.py +++ b/files/tests/test_basic.py @@ -1,4 +1,3 @@ - from . import fixture_accounts from . import util diff --git a/files/tests/test_child_comment_counts.py b/files/tests/test_child_comment_counts.py index 6f53855a4..3871f4ed0 100644 --- a/files/tests/test_child_comment_counts.py +++ b/files/tests/test_child_comment_counts.py @@ -1,3 +1,4 @@ +from files.helpers.const import RENDER_DEPTH_LIMIT from . import fixture_accounts from . import fixture_submissions from . import fixture_comments @@ -158,10 +159,10 @@ def test_more_button_label_in_deep_threads(accounts, submissions, comments): # only look every 5 posts to make this test not _too_ unbearably slow view_post_response = alice_client.get(f'/post/{post.id}') assert 200 == view_post_response.status_code - if i <= 8: - assert f'More comments ({i - 8})' not in view_post_response.text + if i <= RENDER_DEPTH_LIMIT - 1: + assert f'More comments ({i - RENDER_DEPTH_LIMIT + 1})' not in view_post_response.text else: - assert f'More comments ({i - 8})' in view_post_response.text + assert f'More comments ({i - RENDER_DEPTH_LIMIT + 1})' in view_post_response.text @util.no_rate_limit def test_bulk_update_descendant_count_quick(accounts, submissions, comments): diff --git a/files/tests/test_no_content.py b/files/tests/test_no_content.py new file mode 100644 index 000000000..3e336ebdb --- /dev/null +++ b/files/tests/test_no_content.py @@ -0,0 +1,74 @@ +from . import fixture_accounts +from . import util + +@util.no_rate_limit +def test_no_content_submissions(accounts): + client = accounts.client_for_account() + + # get our formkey + submit_get_response = client.get("/submit") + assert submit_get_response.status_code == 200 + + title = '\u200e\u200e\u200e\u200e\u200e\u200e' + body = util.generate_text() + formkey = util.formkey_from(submit_get_response.text) + + # test bad title against good content + submit_post_response = client.post("/submit", data={ + "title": title, + "body": body, + "formkey": formkey, + }) + + assert submit_post_response.status_code == 400 + + title, body = body, title + # test good title against bad content + submit_post_response = client.post("/submit", data={ + "title": title, + "body": body, + "formkey": formkey, + }) + + assert submit_post_response.status_code == 400 + +@util.no_rate_limit +def test_no_content_comments(accounts): + client = accounts.client_for_account() + + # get our formkey + submit_get_response = client.get("/submit") + assert submit_get_response.status_code == 200 + + # make the post + post_title = util.generate_text() + post_body = util.generate_text() + submit_post_response = client.post("/submit", data={ + "title": post_title, + "body": post_body, + "formkey": util.formkey_from(submit_get_response.text), + }) + + assert submit_post_response.status_code == 200 + assert post_title in submit_post_response.text + assert post_body in submit_post_response.text + + # verify it actually got posted + root_response = client.get("/") + assert root_response.status_code == 200 + assert post_title in root_response.text + assert post_body in root_response.text + + # yank the ID out + post = util.ItemData.from_html(submit_post_response.text) + + # post a comment child + comment_body = '\ufeff\ufeff\ufeff\ufeff\ufeff' + submit_comment_response = client.post("/comment", data={ + "parent_fullname": post.id_full, + "parent_level": 1, + "submission": post.id, + "body": comment_body, + "formkey": util.formkey_from(submit_post_response.text), + }) + assert submit_comment_response.status_code == 400 diff --git a/files/tests/test_seed_db.py b/files/tests/test_seed_db.py new file mode 100644 index 000000000..c75502d3e --- /dev/null +++ b/files/tests/test_seed_db.py @@ -0,0 +1,4 @@ +from files.commands.seed_db import seed_db_worker + +def test_seed_db(): + seed_db_worker() diff --git a/migrations/versions/2023_02_08_22_04_15_ba8a214736eb_remove_users_song.py b/migrations/versions/2023_02_08_22_04_15_ba8a214736eb_remove_users_song.py new file mode 100644 index 000000000..bfe6322f2 --- /dev/null +++ b/migrations/versions/2023_02_08_22_04_15_ba8a214736eb_remove_users_song.py @@ -0,0 +1,28 @@ +"""remove users.song + +Revision ID: ba8a214736eb +Revises: 1f30a37b08a0 +Create Date: 2023-02-08 22:04:15.901498+00:00 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'ba8a214736eb' +down_revision = '1f30a37b08a0' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('users', 'song') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('users', sa.Column('song', sa.VARCHAR(length=50), autoincrement=False, nullable=True)) + # ### end Alembic commands ### diff --git a/pg_hba.conf b/pg_hba.conf deleted file mode 100644 index f9537ceb3..000000000 --- a/pg_hba.conf +++ /dev/null @@ -1,44 +0,0 @@ -# Database and user names containing spaces, commas, quotes and other -# special characters must be quoted. Quoting one of the keywords -# "all", "sameuser", "samerole" or "replication" makes the name lose -# its special character, and just match a database or username with -# that name. -# -# This file is read on server startup and when the server receives a -# SIGHUP signal. If you edit the file on a running system, you have to -# SIGHUP the server for the changes to take effect, run "pg_ctl reload", -# or execute "SELECT pg_reload_conf()". -# -# Put your actual configuration here -# ---------------------------------- -# -# If you want to allow non-local connections, you need to add more -# "host" records. In that case you will also need to make PostgreSQL -# listen on a non-local interface via the listen_addresses -# configuration parameter, or via the -i or -h command line switches. - - - - -# DO NOT DISABLE! -# If you change this first entry you will need to make sure that the -# database superuser can access the database using some other method. -# Noninteractive access to all databases is required during automatic -# maintenance (custom daily cronjobs, replication, and similar tasks). -# -# Database administrative login by Unix domain socket -local all postgres trust - -# TYPE DATABASE USER ADDRESS METHOD - -# "local" is for Unix domain socket connections only -local all all trust -# IPv4 local connections: -host all all 127.0.0.1/32 trust -# IPv6 local connections: -host all all ::1/128 trust -# Allow replication connections from localhost, by a user with the -# replication privilege. -local replication all trust -host replication all 127.0.0.1/32 trust -host replication all ::1/128 trust diff --git a/poetry.lock b/poetry.lock index 19cf6d827..ec4ea3666 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1006,14 +1006,6 @@ category = "main" optional = false python-versions = "*" -[[package]] -name = "youtube-dl" -version = "2021.12.17" -description = "YouTube video downloader" -category = "main" -optional = false -python-versions = "*" - [[package]] name = "zope.event" version = "4.5.0" @@ -2228,10 +2220,6 @@ wrapt = [ yattag = [ {file = "yattag-1.14.0.tar.gz", hash = "sha256:5731a31cb7452c0c6930dd1a284e0170b39eee959851a2aceb8d6af4134a5fa8"}, ] -youtube-dl = [ - {file = "youtube_dl-2021.12.17-py2.py3-none-any.whl", hash = "sha256:f1336d5de68647e0364a47b3c0712578e59ec76f02048ff5c50ef1c69d79cd55"}, - {file = "youtube_dl-2021.12.17.tar.gz", hash = "sha256:bc59e86c5d15d887ac590454511f08ce2c47698d5a82c27bfe27b5d814bbaed2"}, -] "zope.event" = [ {file = "zope.event-4.5.0-py2.py3-none-any.whl", hash = "sha256:2666401939cdaa5f4e0c08cf7f20c9b21423b95e88f4675b1443973bdb080c42"}, {file = "zope.event-4.5.0.tar.gz", hash = "sha256:5e76517f5b9b119acf37ca8819781db6c16ea433f7e2062c4afc2b6fbedb1330"}, diff --git a/pyproject.toml b/pyproject.toml index fe939b8e8..e6280f325 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ authors = ["Your Name "] license = "AGPL" [tool.poetry.dependencies] -python = "^3.10" # updating to 3.11 causes instability; see https://github.com/themotte/rDrama/issues/446 +python = "~3.10" # updating to 3.11 causes instability; see https://github.com/themotte/rDrama/issues/446 beautifulsoup4 = "*" bleach = "4.1.0" Flask = "*" @@ -30,11 +30,10 @@ pyotp = "*" qrcode = "*" redis = "*" requests = "*" -SQLAlchemy = "*" +SQLAlchemy = "^1.4.43" user-agents = "*" psycopg2-binary = "*" pusher_push_notifications = "*" -youtube-dl = "*" yattag = "*" webptools = "*" pytest = "*" diff --git a/readme.md b/readme.md index cdbda8a8e..40a920dac 100644 --- a/readme.md +++ b/readme.md @@ -11,13 +11,17 @@ On Windows, Docker will pester you to pay them money for licensing. If you want 2 - Install [Git](https://git-scm.com/). If you're on Windows and want a GUI, [Github Desktop](https://desktop.github.com/) is quite nice. -3 - Run the following commands in the terminal: +3 - Run the following commands in the terminal or command line for first-time setup: -``` +```sh git clone https://github.com/themotte/rDrama/ cd rDrama +``` +4 - Run the following command to start the site: + +```sh docker-compose up --build ``` @@ -41,11 +45,11 @@ Database migrations are instructions for how to convert an out-of-date database ## Why use database migrations -Database migrations allow us to specify where data moves when there are schema changes. This is important when we're live -- if we rename the `comments.ban\_reason` column to `comments.reason\_banned` for naming consistency or whatever, and we do this by dropping the `ban\_reason` column and adding a `reason\_banned` column, we will lose all user data in that column. We don't want to do this. With migrations, we could instead specify that the operation in question should be a column rename, or, if the database engine does not support renaming columns, that we should do a three-step process of "add new column, migrate data over, drop old column". +Database migrations allow us to specify where data moves when there are schema changes. This is important when we're live -- if we rename the `comments.ban_reason` column to `comments.reason_banned` for naming consistency or whatever, and we do this by dropping the `ban_reason` column and adding a `reason_banned` column, we will lose all user data in that column. We don't want to do this. With migrations, we could instead specify that the operation in question should be a column rename, or, if the database engine does not support renaming columns, that we should do a three-step process of "add new column, migrate data over, drop old column". ## Database schema change workflow -As an example, let's say we want to add a column `is\_flagged` to the `comments` table. +As an example, let's say we want to add a column `is_flagged` to the `comments` table. 1. Update the `Comment` model in `files/classes/comment.py` ```python @@ -62,7 +66,7 @@ As an example, let's say we want to add a column `is\_flagged` to the `comments` ./util/command.py db revision --autogenerate --message="add is_flagged field to comments" ``` -This will create a migration in the `migrations/versions` directory with a name like `migrations/versions/2022\_05\_23\_05\_38\_40\_9c27db0b3918\_add\_is\_flagged\_field\_to\_comments.py` and content like +This will create a migration in the `migrations/versions` directory with a name like `migrations/versions/2022_05_23_05_38_40_9c27db0b3918_add_is_flagged_field_to_comments.py` and content like ```python """add is_flagged field to comments Revision ID: 9c27db0b3918 @@ -82,7 +86,7 @@ def downgrade(): op.drop_column('comments', 'is_flagged') ``` -3. Examine the autogenerated migration to make sure that everything looks right (it adds the column you expected it to add and nothing else, all constraints are named, etc. If you see a `None` in one of the alembic operations, e.g. `op.create\_foreign\_key\_something(None, 'usernotes', 'users', ['author\_id'])`, please replace it with a descriptive string before you commit the migration). +3. Examine the autogenerated migration to make sure that everything looks right (it adds the column you expected it to add and nothing else, all constraints are named, etc.) If you see a `None` in one of the alembic operations, e.g. `op.create_foreign_key_something(None, 'usernotes', 'users', ['author_id'])`, please replace it with a descriptive string before you commit the migration. 4. Restart the Docker container to make sure it works. @@ -90,6 +94,6 @@ def downgrade(): docker-compose up --build ``` -## So what's up with schema.sql, can I just change that? +## So what's up with original-schema.sql, can I just change that? No, please do not do that. Instead, please make a migration as described above. diff --git a/redis.conf b/redis.conf deleted file mode 100644 index e048e8d30..000000000 --- a/redis.conf +++ /dev/null @@ -1,1372 +0,0 @@ -# Redis configuration file example. -# -# Note that in order to read the configuration file, Redis must be -# started with the file path as first argument: -# -# ./redis-server /path/to/redis.conf - -# Note on units: when memory size is needed, it is possible to specify -# it in the usual form of 1k 5GB 4M and so forth: -# -# 1k => 1000 bytes -# 1kb => 1024 bytes -# 1m => 1000000 bytes -# 1mb => 1024*1024 bytes -# 1g => 1000000000 bytes -# 1gb => 1024*1024*1024 bytes -# -# units are case insensitive so 1GB 1Gb 1gB are all the same. - -################################## INCLUDES ################################### - -# Include one or more other config files here. This is useful if you -# have a standard template that goes to all Redis servers but also need -# to customize a few per-server settings. Include files can include -# other files, so use this wisely. -# -# Notice option "include" won't be rewritten by command "CONFIG REWRITE" -# from admin or Redis Sentinel. Since Redis always uses the last processed -# line as value of a configuration directive, you'd better put includes -# at the beginning of this file to avoid overwriting config change at runtime. -# -# If instead you are interested in using includes to override configuration -# options, it is better to use include as the last line. -# -# include /path/to/local.conf -# include /path/to/other.conf - -################################## MODULES ##################################### - -# Load modules at startup. If the server is not able to load modules -# it will abort. It is possible to use multiple loadmodule directives. -# -# loadmodule /path/to/my_module.so -# loadmodule /path/to/other_module.so - -################################## NETWORK ##################################### - -# By default, if no "bind" configuration directive is specified, Redis listens -# for connections from all the network interfaces available on the server. -# It is possible to listen to just one or multiple selected interfaces using -# the "bind" configuration directive, followed by one or more IP addresses. -# -# Examples: -# -# bind 192.168.1.100 10.0.0.1 -# bind 127.0.0.1 ::1 -# -# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the -# internet, binding to all the interfaces is dangerous and will expose the -# instance to everybody on the internet. So by default we uncomment the -# following bind directive, that will force Redis to listen only into -# the IPv4 loopback interface address (this means Redis will be able to -# accept connections only from clients running into the same computer it -# is running). -# -# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES -# JUST COMMENT THE FOLLOWING LINE. -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -bind 127.0.0.1 ::1 - -# Protected mode is a layer of security protection, in order to avoid that -# Redis instances left open on the internet are accessed and exploited. -# -# When protected mode is on and if: -# -# 1) The server is not binding explicitly to a set of addresses using the -# "bind" directive. -# 2) No password is configured. -# -# The server only accepts connections from clients connecting from the -# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain -# sockets. -# -# By default protected mode is enabled. You should disable it only if -# you are sure you want clients from other hosts to connect to Redis -# even if no authentication is configured, nor a specific set of interfaces -# are explicitly listed using the "bind" directive. -protected-mode yes - -# Accept connections on the specified port, default is 6379 (IANA #815344). -# If port 0 is specified Redis will not listen on a TCP socket. -port 6379 - -# TCP listen() backlog. -# -# In high requests-per-second environments you need an high backlog in order -# to avoid slow clients connections issues. Note that the Linux kernel -# will silently truncate it to the value of /proc/sys/net/core/somaxconn so -# make sure to raise both the value of somaxconn and tcp_max_syn_backlog -# in order to get the desired effect. -tcp-backlog 511 - -# Unix socket. -# -# Specify the path for the Unix socket that will be used to listen for -# incoming connections. There is no default, so Redis will not listen -# on a unix socket when not specified. -# -# unixsocket /var/run/redis/redis-server.sock -# unixsocketperm 700 - -# Close the connection after a client is idle for N seconds (0 to disable) -timeout 0 - -# TCP keepalive. -# -# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence -# of communication. This is useful for two reasons: -# -# 1) Detect dead peers. -# 2) Take the connection alive from the point of view of network -# equipment in the middle. -# -# On Linux, the specified value (in seconds) is the period used to send ACKs. -# Note that to close the connection the double of the time is needed. -# On other kernels the period depends on the kernel configuration. -# -# A reasonable value for this option is 300 seconds, which is the new -# Redis default starting with Redis 3.2.1. -tcp-keepalive 300 - -################################# GENERAL ##################################### - -# By default Redis does not run as a daemon. Use 'yes' if you need it. -# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. -daemonize yes - -# If you run Redis from upstart or systemd, Redis can interact with your -# supervision tree. Options: -# supervised no - no supervision interaction -# supervised upstart - signal upstart by putting Redis into SIGSTOP mode -# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET -# supervised auto - detect upstart or systemd method based on -# UPSTART_JOB or NOTIFY_SOCKET environment variables -# Note: these supervision methods only signal "process is ready." -# They do not enable continuous liveness pings back to your supervisor. -supervised systemd - -# If a pid file is specified, Redis writes it where specified at startup -# and removes it at exit. -# -# When the server runs non daemonized, no pid file is created if none is -# specified in the configuration. When the server is daemonized, the pid file -# is used even if not specified, defaulting to "/var/run/redis.pid". -# -# Creating a pid file is best effort: if Redis is not able to create it -# nothing bad happens, the server will start and run normally. -pidfile /var/run/redis/redis-server.pid - -# Specify the server verbosity level. -# This can be one of: -# debug (a lot of information, useful for development/testing) -# verbose (many rarely useful info, but not a mess like the debug level) -# notice (moderately verbose, what you want in production probably) -# warning (only very important / critical messages are logged) -loglevel notice - -# Specify the log file name. Also the empty string can be used to force -# Redis to log on the standard output. Note that if you use standard -# output for logging but daemonize, logs will be sent to /dev/null -logfile /var/log/redis/redis-server.log - -# To enable logging to the system logger, just set 'syslog-enabled' to yes, -# and optionally update the other syslog parameters to suit your needs. -# syslog-enabled no - -# Specify the syslog identity. -# syslog-ident redis - -# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. -# syslog-facility local0 - -# Set the number of databases. The default database is DB 0, you can select -# a different one on a per-connection basis using SELECT where -# dbid is a number between 0 and 'databases'-1 -databases 16 - -# By default Redis shows an ASCII art logo only when started to log to the -# standard output and if the standard output is a TTY. Basically this means -# that normally a logo is displayed only in interactive sessions. -# -# However it is possible to force the pre-4.0 behavior and always show a -# ASCII art logo in startup logs by setting the following option to yes. -always-show-logo yes - -################################ SNAPSHOTTING ################################ -# -# Save the DB on disk: -# -# save -# -# Will save the DB if both the given number of seconds and the given -# number of write operations against the DB occurred. -# -# In the example below the behaviour will be to save: -# after 900 sec (15 min) if at least 1 key changed -# after 300 sec (5 min) if at least 10 keys changed -# after 60 sec if at least 10000 keys changed -# -# Note: you can disable saving completely by commenting out all "save" lines. -# -# It is also possible to remove all the previously configured save -# points by adding a save directive with a single empty string argument -# like in the following example: -# -# save "" - -save 900 1 -save 300 10 -save 60 10000 - -# By default Redis will stop accepting writes if RDB snapshots are enabled -# (at least one save point) and the latest background save failed. -# This will make the user aware (in a hard way) that data is not persisting -# on disk properly, otherwise chances are that no one will notice and some -# disaster will happen. -# -# If the background saving process will start working again Redis will -# automatically allow writes again. -# -# However if you have setup your proper monitoring of the Redis server -# and persistence, you may want to disable this feature so that Redis will -# continue to work as usual even if there are problems with disk, -# permissions, and so forth. -stop-writes-on-bgsave-error yes - -# Compress string objects using LZF when dump .rdb databases? -# For default that's set to 'yes' as it's almost always a win. -# If you want to save some CPU in the saving child set it to 'no' but -# the dataset will likely be bigger if you have compressible values or keys. -rdbcompression yes - -# Since version 5 of RDB a CRC64 checksum is placed at the end of the file. -# This makes the format more resistant to corruption but there is a performance -# hit to pay (around 10%) when saving and loading RDB files, so you can disable it -# for maximum performances. -# -# RDB files created with checksum disabled have a checksum of zero that will -# tell the loading code to skip the check. -rdbchecksum yes - -# The filename where to dump the DB -dbfilename dump.rdb - -# The working directory. -# -# The DB will be written inside this directory, with the filename specified -# above using the 'dbfilename' configuration directive. -# -# The Append Only File will also be created inside this directory. -# -# Note that you must specify a directory here, not a file name. -dir /var/lib/redis - -################################# REPLICATION ################################# - -# Master-Replica replication. Use replicaof to make a Redis instance a copy of -# another Redis server. A few things to understand ASAP about Redis replication. -# -# +------------------+ +---------------+ -# | Master | ---> | Replica | -# | (receive writes) | | (exact copy) | -# +------------------+ +---------------+ -# -# 1) Redis replication is asynchronous, but you can configure a master to -# stop accepting writes if it appears to be not connected with at least -# a given number of replicas. -# 2) Redis replicas are able to perform a partial resynchronization with the -# master if the replication link is lost for a relatively small amount of -# time. You may want to configure the replication backlog size (see the next -# sections of this file) with a sensible value depending on your needs. -# 3) Replication is automatic and does not need user intervention. After a -# network partition replicas automatically try to reconnect to masters -# and resynchronize with them. -# -# replicaof - -# If the master is password protected (using the "requirepass" configuration -# directive below) it is possible to tell the replica to authenticate before -# starting the replication synchronization process, otherwise the master will -# refuse the replica request. -# -# masterauth - -# When a replica loses its connection with the master, or when the replication -# is still in progress, the replica can act in two different ways: -# -# 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will -# still reply to client requests, possibly with out of date data, or the -# data set may just be empty if this is the first synchronization. -# -# 2) if replica-serve-stale-data is set to 'no' the replica will reply with -# an error "SYNC with master in progress" to all the kind of commands -# but to INFO, replicaOF, AUTH, PING, SHUTDOWN, REPLCONF, ROLE, CONFIG, -# SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB, -# COMMAND, POST, HOST: and LATENCY. -# -replica-serve-stale-data yes - -# You can configure a replica instance to accept writes or not. Writing against -# a replica instance may be useful to store some ephemeral data (because data -# written on a replica will be easily deleted after resync with the master) but -# may also cause problems if clients are writing to it because of a -# misconfiguration. -# -# Since Redis 2.6 by default replicas are read-only. -# -# Note: read only replicas are not designed to be exposed to untrusted clients -# on the internet. It's just a protection layer against misuse of the instance. -# Still a read only replica exports by default all the administrative commands -# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve -# security of read only replicas using 'rename-command' to shadow all the -# administrative / dangerous commands. -replica-read-only yes - -# Replication SYNC strategy: disk or socket. -# -# ------------------------------------------------------- -# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY -# ------------------------------------------------------- -# -# New replicas and reconnecting replicas that are not able to continue the replication -# process just receiving differences, need to do what is called a "full -# synchronization". An RDB file is transmitted from the master to the replicas. -# The transmission can happen in two different ways: -# -# 1) Disk-backed: The Redis master creates a new process that writes the RDB -# file on disk. Later the file is transferred by the parent -# process to the replicas incrementally. -# 2) Diskless: The Redis master creates a new process that directly writes the -# RDB file to replica sockets, without touching the disk at all. -# -# With disk-backed replication, while the RDB file is generated, more replicas -# can be queued and served with the RDB file as soon as the current child producing -# the RDB file finishes its work. With diskless replication instead once -# the transfer starts, new replicas arriving will be queued and a new transfer -# will start when the current one terminates. -# -# When diskless replication is used, the master waits a configurable amount of -# time (in seconds) before starting the transfer in the hope that multiple replicas -# will arrive and the transfer can be parallelized. -# -# With slow disks and fast (large bandwidth) networks, diskless replication -# works better. -repl-diskless-sync no - -# When diskless replication is enabled, it is possible to configure the delay -# the server waits in order to spawn the child that transfers the RDB via socket -# to the replicas. -# -# This is important since once the transfer starts, it is not possible to serve -# new replicas arriving, that will be queued for the next RDB transfer, so the server -# waits a delay in order to let more replicas arrive. -# -# The delay is specified in seconds, and by default is 5 seconds. To disable -# it entirely just set it to 0 seconds and the transfer will start ASAP. -repl-diskless-sync-delay 5 - -# Replicas send PINGs to server in a predefined interval. It's possible to change -# this interval with the repl_ping_replica_period option. The default value is 10 -# seconds. -# -# repl-ping-replica-period 10 - -# The following option sets the replication timeout for: -# -# 1) Bulk transfer I/O during SYNC, from the point of view of replica. -# 2) Master timeout from the point of view of replicas (data, pings). -# 3) Replica timeout from the point of view of masters (REPLCONF ACK pings). -# -# It is important to make sure that this value is greater than the value -# specified for repl-ping-replica-period otherwise a timeout will be detected -# every time there is low traffic between the master and the replica. -# -# repl-timeout 60 - -# Disable TCP_NODELAY on the replica socket after SYNC? -# -# If you select "yes" Redis will use a smaller number of TCP packets and -# less bandwidth to send data to replicas. But this can add a delay for -# the data to appear on the replica side, up to 40 milliseconds with -# Linux kernels using a default configuration. -# -# If you select "no" the delay for data to appear on the replica side will -# be reduced but more bandwidth will be used for replication. -# -# By default we optimize for low latency, but in very high traffic conditions -# or when the master and replicas are many hops away, turning this to "yes" may -# be a good idea. -repl-disable-tcp-nodelay no - -# Set the replication backlog size. The backlog is a buffer that accumulates -# replica data when replicas are disconnected for some time, so that when a replica -# wants to reconnect again, often a full resync is not needed, but a partial -# resync is enough, just passing the portion of data the replica missed while -# disconnected. -# -# The bigger the replication backlog, the longer the time the replica can be -# disconnected and later be able to perform a partial resynchronization. -# -# The backlog is only allocated once there is at least a replica connected. -# -# repl-backlog-size 1mb - -# After a master has no longer connected replicas for some time, the backlog -# will be freed. The following option configures the amount of seconds that -# need to elapse, starting from the time the last replica disconnected, for -# the backlog buffer to be freed. -# -# Note that replicas never free the backlog for timeout, since they may be -# promoted to masters later, and should be able to correctly "partially -# resynchronize" with the replicas: hence they should always accumulate backlog. -# -# A value of 0 means to never release the backlog. -# -# repl-backlog-ttl 3600 - -# The replica priority is an integer number published by Redis in the INFO output. -# It is used by Redis Sentinel in order to select a replica to promote into a -# master if the master is no longer working correctly. -# -# A replica with a low priority number is considered better for promotion, so -# for instance if there are three replicas with priority 10, 100, 25 Sentinel will -# pick the one with priority 10, that is the lowest. -# -# However a special priority of 0 marks the replica as not able to perform the -# role of master, so a replica with priority of 0 will never be selected by -# Redis Sentinel for promotion. -# -# By default the priority is 100. -replica-priority 100 - -# It is possible for a master to stop accepting writes if there are less than -# N replicas connected, having a lag less or equal than M seconds. -# -# The N replicas need to be in "online" state. -# -# The lag in seconds, that must be <= the specified value, is calculated from -# the last ping received from the replica, that is usually sent every second. -# -# This option does not GUARANTEE that N replicas will accept the write, but -# will limit the window of exposure for lost writes in case not enough replicas -# are available, to the specified number of seconds. -# -# For example to require at least 3 replicas with a lag <= 10 seconds use: -# -# min-replicas-to-write 3 -# min-replicas-max-lag 10 -# -# Setting one or the other to 0 disables the feature. -# -# By default min-replicas-to-write is set to 0 (feature disabled) and -# min-replicas-max-lag is set to 10. - -# A Redis master is able to list the address and port of the attached -# replicas in different ways. For example the "INFO replication" section -# offers this information, which is used, among other tools, by -# Redis Sentinel in order to discover replica instances. -# Another place where this info is available is in the output of the -# "ROLE" command of a master. -# -# The listed IP and address normally reported by a replica is obtained -# in the following way: -# -# IP: The address is auto detected by checking the peer address -# of the socket used by the replica to connect with the master. -# -# Port: The port is communicated by the replica during the replication -# handshake, and is normally the port that the replica is using to -# listen for connections. -# -# However when port forwarding or Network Address Translation (NAT) is -# used, the replica may be actually reachable via different IP and port -# pairs. The following two options can be used by a replica in order to -# report to its master a specific set of IP and port, so that both INFO -# and ROLE will report those values. -# -# There is no need to use both the options if you need to override just -# the port or the IP address. -# -# replica-announce-ip 5.5.5.5 -# replica-announce-port 1234 - -################################## SECURITY ################################### - -# Require clients to issue AUTH before processing any other -# commands. This might be useful in environments in which you do not trust -# others with access to the host running redis-server. -# -# This should stay commented out for backward compatibility and because most -# people do not need auth (e.g. they run their own servers). -# -# Warning: since Redis is pretty fast an outside user can try up to -# 150k passwords per second against a good box. This means that you should -# use a very strong password otherwise it will be very easy to break. -# -# requirepass foobared - -# Command renaming. -# -# It is possible to change the name of dangerous commands in a shared -# environment. For instance the CONFIG command may be renamed into something -# hard to guess so that it will still be available for internal-use tools -# but not available for general clients. -# -# Example: -# -# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 -# -# It is also possible to completely kill a command by renaming it into -# an empty string: -# -# rename-command CONFIG "" -# -# Please note that changing the name of commands that are logged into the -# AOF file or transmitted to replicas may cause problems. - -################################### CLIENTS #################################### - -# Set the max number of connected clients at the same time. By default -# this limit is set to 10000 clients, however if the Redis server is not -# able to configure the process file limit to allow for the specified limit -# the max number of allowed clients is set to the current file limit -# minus 32 (as Redis reserves a few file descriptors for internal uses). -# -# Once the limit is reached Redis will close all the new connections sending -# an error 'max number of clients reached'. -# -# maxclients 10000 - -############################## MEMORY MANAGEMENT ################################ - -# Set a memory usage limit to the specified amount of bytes. -# When the memory limit is reached Redis will try to remove keys -# according to the eviction policy selected (see maxmemory-policy). -# -# If Redis can't remove keys according to the policy, or if the policy is -# set to 'noeviction', Redis will start to reply with errors to commands -# that would use more memory, like SET, LPUSH, and so on, and will continue -# to reply to read-only commands like GET. -# -# This option is usually useful when using Redis as an LRU or LFU cache, or to -# set a hard memory limit for an instance (using the 'noeviction' policy). -# -# WARNING: If you have replicas attached to an instance with maxmemory on, -# the size of the output buffers needed to feed the replicas are subtracted -# from the used memory count, so that network problems / resyncs will -# not trigger a loop where keys are evicted, and in turn the output -# buffer of replicas is full with DELs of keys evicted triggering the deletion -# of more keys, and so forth until the database is completely emptied. -# -# In short... if you have replicas attached it is suggested that you set a lower -# limit for maxmemory so that there is some free RAM on the system for replica -# output buffers (but this is not needed if the policy is 'noeviction'). -# -# maxmemory - -# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory -# is reached. You can select among five behaviors: -# -# volatile-lru -> Evict using approximated LRU among the keys with an expire set. -# allkeys-lru -> Evict any key using approximated LRU. -# volatile-lfu -> Evict using approximated LFU among the keys with an expire set. -# allkeys-lfu -> Evict any key using approximated LFU. -# volatile-random -> Remove a random key among the ones with an expire set. -# allkeys-random -> Remove a random key, any key. -# volatile-ttl -> Remove the key with the nearest expire time (minor TTL) -# noeviction -> Don't evict anything, just return an error on write operations. -# -# LRU means Least Recently Used -# LFU means Least Frequently Used -# -# Both LRU, LFU and volatile-ttl are implemented using approximated -# randomized algorithms. -# -# Note: with any of the above policies, Redis will return an error on write -# operations, when there are no suitable keys for eviction. -# -# At the date of writing these commands are: set setnx setex append -# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd -# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby -# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby -# getset mset msetnx exec sort -# -# The default is: -# -# maxmemory-policy noeviction - -# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated -# algorithms (in order to save memory), so you can tune it for speed or -# accuracy. For default Redis will check five keys and pick the one that was -# used less recently, you can change the sample size using the following -# configuration directive. -# -# The default of 5 produces good enough results. 10 Approximates very closely -# true LRU but costs more CPU. 3 is faster but not very accurate. -# -# maxmemory-samples 5 - -# Starting from Redis 5, by default a replica will ignore its maxmemory setting -# (unless it is promoted to master after a failover or manually). It means -# that the eviction of keys will be just handled by the master, sending the -# DEL commands to the replica as keys evict in the master side. -# -# This behavior ensures that masters and replicas stay consistent, and is usually -# what you want, however if your replica is writable, or you want the replica to have -# a different memory setting, and you are sure all the writes performed to the -# replica are idempotent, then you may change this default (but be sure to understand -# what you are doing). -# -# Note that since the replica by default does not evict, it may end using more -# memory than the one set via maxmemory (there are certain buffers that may -# be larger on the replica, or data structures may sometimes take more memory and so -# forth). So make sure you monitor your replicas and make sure they have enough -# memory to never hit a real out-of-memory condition before the master hits -# the configured maxmemory setting. -# -# replica-ignore-maxmemory yes - -############################# LAZY FREEING #################################### - -# Redis has two primitives to delete keys. One is called DEL and is a blocking -# deletion of the object. It means that the server stops processing new commands -# in order to reclaim all the memory associated with an object in a synchronous -# way. If the key deleted is associated with a small object, the time needed -# in order to execute the DEL command is very small and comparable to most other -# O(1) or O(log_N) commands in Redis. However if the key is associated with an -# aggregated value containing millions of elements, the server can block for -# a long time (even seconds) in order to complete the operation. -# -# For the above reasons Redis also offers non blocking deletion primitives -# such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and -# FLUSHDB commands, in order to reclaim memory in background. Those commands -# are executed in constant time. Another thread will incrementally free the -# object in the background as fast as possible. -# -# DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled. -# It's up to the design of the application to understand when it is a good -# idea to use one or the other. However the Redis server sometimes has to -# delete keys or flush the whole database as a side effect of other operations. -# Specifically Redis deletes objects independently of a user call in the -# following scenarios: -# -# 1) On eviction, because of the maxmemory and maxmemory policy configurations, -# in order to make room for new data, without going over the specified -# memory limit. -# 2) Because of expire: when a key with an associated time to live (see the -# EXPIRE command) must be deleted from memory. -# 3) Because of a side effect of a command that stores data on a key that may -# already exist. For example the RENAME command may delete the old key -# content when it is replaced with another one. Similarly SUNIONSTORE -# or SORT with STORE option may delete existing keys. The SET command -# itself removes any old content of the specified key in order to replace -# it with the specified string. -# 4) During replication, when a replica performs a full resynchronization with -# its master, the content of the whole database is removed in order to -# load the RDB file just transferred. -# -# In all the above cases the default is to delete objects in a blocking way, -# like if DEL was called. However you can configure each case specifically -# in order to instead release memory in a non-blocking way like if UNLINK -# was called, using the following configuration directives: - -lazyfree-lazy-eviction no -lazyfree-lazy-expire no -lazyfree-lazy-server-del no -replica-lazy-flush no - -############################## APPEND ONLY MODE ############################### - -# By default Redis asynchronously dumps the dataset on disk. This mode is -# good enough in many applications, but an issue with the Redis process or -# a power outage may result into a few minutes of writes lost (depending on -# the configured save points). -# -# The Append Only File is an alternative persistence mode that provides -# much better durability. For instance using the default data fsync policy -# (see later in the config file) Redis can lose just one second of writes in a -# dramatic event like a server power outage, or a single write if something -# wrong with the Redis process itself happens, but the operating system is -# still running correctly. -# -# AOF and RDB persistence can be enabled at the same time without problems. -# If the AOF is enabled on startup Redis will load the AOF, that is the file -# with the better durability guarantees. -# -# Please check https://redis.io/topics/persistence for more information. - -appendonly no - -# The name of the append only file (default: "appendonly.aof") - -appendfilename "appendonly.aof" - -# The fsync() call tells the Operating System to actually write data on disk -# instead of waiting for more data in the output buffer. Some OS will really flush -# data on disk, some other OS will just try to do it ASAP. -# -# Redis supports three different modes: -# -# no: don't fsync, just let the OS flush the data when it wants. Faster. -# always: fsync after every write to the append only log. Slow, Safest. -# everysec: fsync only one time every second. Compromise. -# -# The default is "everysec", as that's usually the right compromise between -# speed and data safety. It's up to you to understand if you can relax this to -# "no" that will let the operating system flush the output buffer when -# it wants, for better performances (but if you can live with the idea of -# some data loss consider the default persistence mode that's snapshotting), -# or on the contrary, use "always" that's very slow but a bit safer than -# everysec. -# -# More details please check the following article: -# https://antirez.com/post/redis-persistence-demystified.html -# -# If unsure, use "everysec". - -# appendfsync always -appendfsync everysec -# appendfsync no - -# When the AOF fsync policy is set to always or everysec, and a background -# saving process (a background save or AOF log background rewriting) is -# performing a lot of I/O against the disk, in some Linux configurations -# Redis may block too long on the fsync() call. Note that there is no fix for -# this currently, as even performing fsync in a different thread will block -# our synchronous write(2) call. -# -# In order to mitigate this problem it's possible to use the following option -# that will prevent fsync() from being called in the main process while a -# BGSAVE or BGREWRITEAOF is in progress. -# -# This means that while another child is saving, the durability of Redis is -# the same as "appendfsync none". In practical terms, this means that it is -# possible to lose up to 30 seconds of log in the worst scenario (with the -# default Linux settings). -# -# If you have latency problems turn this to "yes". Otherwise leave it as -# "no" that is the safest pick from the point of view of durability. - -no-appendfsync-on-rewrite no - -# Automatic rewrite of the append only file. -# Redis is able to automatically rewrite the log file implicitly calling -# BGREWRITEAOF when the AOF log size grows by the specified percentage. -# -# This is how it works: Redis remembers the size of the AOF file after the -# latest rewrite (if no rewrite has happened since the restart, the size of -# the AOF at startup is used). -# -# This base size is compared to the current size. If the current size is -# bigger than the specified percentage, the rewrite is triggered. Also -# you need to specify a minimal size for the AOF file to be rewritten, this -# is useful to avoid rewriting the AOF file even if the percentage increase -# is reached but it is still pretty small. -# -# Specify a percentage of zero in order to disable the automatic AOF -# rewrite feature. - -auto-aof-rewrite-percentage 100 -auto-aof-rewrite-min-size 64mb - -# An AOF file may be found to be truncated at the end during the Redis -# startup process, when the AOF data gets loaded back into memory. -# This may happen when the system where Redis is running -# crashes, especially when an ext4 filesystem is mounted without the -# data=ordered option (however this can't happen when Redis itself -# crashes or aborts but the operating system still works correctly). -# -# Redis can either exit with an error when this happens, or load as much -# data as possible (the default now) and start if the AOF file is found -# to be truncated at the end. The following option controls this behavior. -# -# If aof-load-truncated is set to yes, a truncated AOF file is loaded and -# the Redis server starts emitting a log to inform the user of the event. -# Otherwise if the option is set to no, the server aborts with an error -# and refuses to start. When the option is set to no, the user requires -# to fix the AOF file using the "redis-check-aof" utility before to restart -# the server. -# -# Note that if the AOF file will be found to be corrupted in the middle -# the server will still exit with an error. This option only applies when -# Redis will try to read more data from the AOF file but not enough bytes -# will be found. -aof-load-truncated yes - -# When rewriting the AOF file, Redis is able to use an RDB preamble in the -# AOF file for faster rewrites and recoveries. When this option is turned -# on the rewritten AOF file is composed of two different stanzas: -# -# [RDB file][AOF tail] -# -# When loading Redis recognizes that the AOF file starts with the "REDIS" -# string and loads the prefixed RDB file, and continues loading the AOF -# tail. -aof-use-rdb-preamble yes - -################################ LUA SCRIPTING ############################### - -# Max execution time of a Lua script in milliseconds. -# -# If the maximum execution time is reached Redis will log that a script is -# still in execution after the maximum allowed time and will start to -# reply to queries with an error. -# -# When a long running script exceeds the maximum execution time only the -# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be -# used to stop a script that did not yet called write commands. The second -# is the only way to shut down the server in the case a write command was -# already issued by the script but the user doesn't want to wait for the natural -# termination of the script. -# -# Set it to 0 or a negative value for unlimited execution without warnings. -lua-time-limit 5000 - -################################ REDIS CLUSTER ############################### - -# Normal Redis instances can't be part of a Redis Cluster; only nodes that are -# started as cluster nodes can. In order to start a Redis instance as a -# cluster node enable the cluster support uncommenting the following: -# -# cluster-enabled yes - -# Every cluster node has a cluster configuration file. This file is not -# intended to be edited by hand. It is created and updated by Redis nodes. -# Every Redis Cluster node requires a different cluster configuration file. -# Make sure that instances running in the same system do not have -# overlapping cluster configuration file names. -# -# cluster-config-file nodes-6379.conf - -# Cluster node timeout is the amount of milliseconds a node must be unreachable -# for it to be considered in failure state. -# Most other internal time limits are multiple of the node timeout. -# -# cluster-node-timeout 15000 - -# A replica of a failing master will avoid to start a failover if its data -# looks too old. -# -# There is no simple way for a replica to actually have an exact measure of -# its "data age", so the following two checks are performed: -# -# 1) If there are multiple replicas able to failover, they exchange messages -# in order to try to give an advantage to the replica with the best -# replication offset (more data from the master processed). -# Replicas will try to get their rank by offset, and apply to the start -# of the failover a delay proportional to their rank. -# -# 2) Every single replica computes the time of the last interaction with -# its master. This can be the last ping or command received (if the master -# is still in the "connected" state), or the time that elapsed since the -# disconnection with the master (if the replication link is currently down). -# If the last interaction is too old, the replica will not try to failover -# at all. -# -# The point "2" can be tuned by user. Specifically a replica will not perform -# the failover if, since the last interaction with the master, the time -# elapsed is greater than: -# -# (node-timeout * replica-validity-factor) + repl-ping-replica-period -# -# So for example if node-timeout is 30 seconds, and the replica-validity-factor -# is 10, and assuming a default repl-ping-replica-period of 10 seconds, the -# replica will not try to failover if it was not able to talk with the master -# for longer than 310 seconds. -# -# A large replica-validity-factor may allow replicas with too old data to failover -# a master, while a too small value may prevent the cluster from being able to -# elect a replica at all. -# -# For maximum availability, it is possible to set the replica-validity-factor -# to a value of 0, which means, that replicas will always try to failover the -# master regardless of the last time they interacted with the master. -# (However they'll always try to apply a delay proportional to their -# offset rank). -# -# Zero is the only value able to guarantee that when all the partitions heal -# the cluster will always be able to continue. -# -# cluster-replica-validity-factor 10 - -# Cluster replicas are able to migrate to orphaned masters, that are masters -# that are left without working replicas. This improves the cluster ability -# to resist to failures as otherwise an orphaned master can't be failed over -# in case of failure if it has no working replicas. -# -# Replicas migrate to orphaned masters only if there are still at least a -# given number of other working replicas for their old master. This number -# is the "migration barrier". A migration barrier of 1 means that a replica -# will migrate only if there is at least 1 other working replica for its master -# and so forth. It usually reflects the number of replicas you want for every -# master in your cluster. -# -# Default is 1 (replicas migrate only if their masters remain with at least -# one replica). To disable migration just set it to a very large value. -# A value of 0 can be set but is useful only for debugging and dangerous -# in production. -# -# cluster-migration-barrier 1 - -# By default Redis Cluster nodes stop accepting queries if they detect there -# is at least an hash slot uncovered (no available node is serving it). -# This way if the cluster is partially down (for example a range of hash slots -# are no longer covered) all the cluster becomes, eventually, unavailable. -# It automatically returns available as soon as all the slots are covered again. -# -# However sometimes you want the subset of the cluster which is working, -# to continue to accept queries for the part of the key space that is still -# covered. In order to do so, just set the cluster-require-full-coverage -# option to no. -# -# cluster-require-full-coverage yes - -# This option, when set to yes, prevents replicas from trying to failover its -# master during master failures. However the master can still perform a -# manual failover, if forced to do so. -# -# This is useful in different scenarios, especially in the case of multiple -# data center operations, where we want one side to never be promoted if not -# in the case of a total DC failure. -# -# cluster-replica-no-failover no - -# In order to setup your cluster make sure to read the documentation -# available at https://redis.io web site. - -########################## CLUSTER DOCKER/NAT support ######################## - -# In certain deployments, Redis Cluster nodes address discovery fails, because -# addresses are NAT-ted or because ports are forwarded (the typical case is -# Docker and other containers). -# -# In order to make Redis Cluster working in such environments, a static -# configuration where each node knows its public address is needed. The -# following two options are used for this scope, and are: -# -# * cluster-announce-ip -# * cluster-announce-port -# * cluster-announce-bus-port -# -# Each instruct the node about its address, client port, and cluster message -# bus port. The information is then published in the header of the bus packets -# so that other nodes will be able to correctly map the address of the node -# publishing the information. -# -# If the above options are not used, the normal Redis Cluster auto-detection -# will be used instead. -# -# Note that when remapped, the bus port may not be at the fixed offset of -# clients port + 10000, so you can specify any port and bus-port depending -# on how they get remapped. If the bus-port is not set, a fixed offset of -# 10000 will be used as usually. -# -# Example: -# -# cluster-announce-ip 10.1.1.5 -# cluster-announce-port 6379 -# cluster-announce-bus-port 6380 - -################################## SLOW LOG ################################### - -# The Redis Slow Log is a system to log queries that exceeded a specified -# execution time. The execution time does not include the I/O operations -# like talking with the client, sending the reply and so forth, -# but just the time needed to actually execute the command (this is the only -# stage of command execution where the thread is blocked and can not serve -# other requests in the meantime). -# -# You can configure the slow log with two parameters: one tells Redis -# what is the execution time, in microseconds, to exceed in order for the -# command to get logged, and the other parameter is the length of the -# slow log. When a new command is logged the oldest one is removed from the -# queue of logged commands. - -# The following time is expressed in microseconds, so 1000000 is equivalent -# to one second. Note that a negative number disables the slow log, while -# a value of zero forces the logging of every command. -slowlog-log-slower-than 10000 - -# There is no limit to this length. Just be aware that it will consume memory. -# You can reclaim memory used by the slow log with SLOWLOG RESET. -slowlog-max-len 128 - -################################ LATENCY MONITOR ############################## - -# The Redis latency monitoring subsystem samples different operations -# at runtime in order to collect data related to possible sources of -# latency of a Redis instance. -# -# Via the LATENCY command this information is available to the user that can -# print graphs and obtain reports. -# -# The system only logs operations that were performed in a time equal or -# greater than the amount of milliseconds specified via the -# latency-monitor-threshold configuration directive. When its value is set -# to zero, the latency monitor is turned off. -# -# By default latency monitoring is disabled since it is mostly not needed -# if you don't have latency issues, and collecting data has a performance -# impact, that while very small, can be measured under big load. Latency -# monitoring can easily be enabled at runtime using the command -# "CONFIG SET latency-monitor-threshold " if needed. -latency-monitor-threshold 0 - -############################# EVENT NOTIFICATION ############################## - -# Redis can notify Pub/Sub clients about events happening in the key space. -# This feature is documented at https://redis.io/topics/notifications -# -# For instance if keyspace events notification is enabled, and a client -# performs a DEL operation on key "foo" stored in the Database 0, two -# messages will be published via Pub/Sub: -# -# PUBLISH __keyspace@0__:foo del -# PUBLISH __keyevent@0__:del foo -# -# It is possible to select the events that Redis will notify among a set -# of classes. Every class is identified by a single character: -# -# K Keyspace events, published with __keyspace@__ prefix. -# E Keyevent events, published with __keyevent@__ prefix. -# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... -# $ String commands -# l List commands -# s Set commands -# h Hash commands -# z Sorted set commands -# x Expired events (events generated every time a key expires) -# e Evicted events (events generated when a key is evicted for maxmemory) -# A Alias for g$lshzxe, so that the "AKE" string means all the events. -# -# The "notify-keyspace-events" takes as argument a string that is composed -# of zero or multiple characters. The empty string means that notifications -# are disabled. -# -# Example: to enable list and generic events, from the point of view of the -# event name, use: -# -# notify-keyspace-events Elg -# -# Example 2: to get the stream of the expired keys subscribing to channel -# name __keyevent@0__:expired use: -# -# notify-keyspace-events Ex -# -# By default all notifications are disabled because most users don't need -# this feature and the feature has some overhead. Note that if you don't -# specify at least one of K or E, no events will be delivered. -notify-keyspace-events "" - -############################### ADVANCED CONFIG ############################### - -# Hashes are encoded using a memory efficient data structure when they have a -# small number of entries, and the biggest entry does not exceed a given -# threshold. These thresholds can be configured using the following directives. -hash-max-ziplist-entries 512 -hash-max-ziplist-value 64 - -# Lists are also encoded in a special way to save a lot of space. -# The number of entries allowed per internal list node can be specified -# as a fixed maximum size or a maximum number of elements. -# For a fixed maximum size, use -5 through -1, meaning: -# -5: max size: 64 Kb <-- not recommended for normal workloads -# -4: max size: 32 Kb <-- not recommended -# -3: max size: 16 Kb <-- probably not recommended -# -2: max size: 8 Kb <-- good -# -1: max size: 4 Kb <-- good -# Positive numbers mean store up to _exactly_ that number of elements -# per list node. -# The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size), -# but if your use case is unique, adjust the settings as necessary. -list-max-ziplist-size -2 - -# Lists may also be compressed. -# Compress depth is the number of quicklist ziplist nodes from *each* side of -# the list to *exclude* from compression. The head and tail of the list -# are always uncompressed for fast push/pop operations. Settings are: -# 0: disable all list compression -# 1: depth 1 means "don't start compressing until after 1 node into the list, -# going from either the head or tail" -# So: [head]->node->node->...->node->[tail] -# [head], [tail] will always be uncompressed; inner nodes will compress. -# 2: [head]->[next]->node->node->...->node->[prev]->[tail] -# 2 here means: don't compress head or head->next or tail->prev or tail, -# but compress all nodes between them. -# 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] -# etc. -list-compress-depth 0 - -# Sets have a special encoding in just one case: when a set is composed -# of just strings that happen to be integers in radix 10 in the range -# of 64 bit signed integers. -# The following configuration setting sets the limit in the size of the -# set in order to use this special memory saving encoding. -set-max-intset-entries 512 - -# Similarly to hashes and lists, sorted sets are also specially encoded in -# order to save a lot of space. This encoding is only used when the length and -# elements of a sorted set are below the following limits: -zset-max-ziplist-entries 128 -zset-max-ziplist-value 64 - -# HyperLogLog sparse representation bytes limit. The limit includes the -# 16 bytes header. When an HyperLogLog using the sparse representation crosses -# this limit, it is converted into the dense representation. -# -# A value greater than 16000 is totally useless, since at that point the -# dense representation is more memory efficient. -# -# The suggested value is ~ 3000 in order to have the benefits of -# the space efficient encoding without slowing down too much PFADD, -# which is O(N) with the sparse encoding. The value can be raised to -# ~ 10000 when CPU is not a concern, but space is, and the data set is -# composed of many HyperLogLogs with cardinality in the 0 - 15000 range. -hll-sparse-max-bytes 3000 - -# Streams macro node max size / items. The stream data structure is a radix -# tree of big nodes that encode multiple items inside. Using this configuration -# it is possible to configure how big a single node can be in bytes, and the -# maximum number of items it may contain before switching to a new node when -# appending new stream entries. If any of the following settings are set to -# zero, the limit is ignored, so for instance it is possible to set just a -# max entires limit by setting max-bytes to 0 and max-entries to the desired -# value. -stream-node-max-bytes 4096 -stream-node-max-entries 100 - -# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in -# order to help rehashing the main Redis hash table (the one mapping top-level -# keys to values). The hash table implementation Redis uses (see dict.c) -# performs a lazy rehashing: the more operation you run into a hash table -# that is rehashing, the more rehashing "steps" are performed, so if the -# server is idle the rehashing is never complete and some more memory is used -# by the hash table. -# -# The default is to use this millisecond 10 times every second in order to -# actively rehash the main dictionaries, freeing memory when possible. -# -# If unsure: -# use "activerehashing no" if you have hard latency requirements and it is -# not a good thing in your environment that Redis can reply from time to time -# to queries with 2 milliseconds delay. -# -# use "activerehashing yes" if you don't have such hard requirements but -# want to free memory asap when possible. -activerehashing yes - -# The client output buffer limits can be used to force disconnection of clients -# that are not reading data from the server fast enough for some reason (a -# common reason is that a Pub/Sub client can't consume messages as fast as the -# publisher can produce them). -# -# The limit can be set differently for the three different classes of clients: -# -# normal -> normal clients including MONITOR clients -# replica -> replica clients -# pubsub -> clients subscribed to at least one pubsub channel or pattern -# -# The syntax of every client-output-buffer-limit directive is the following: -# -# client-output-buffer-limit -# -# A client is immediately disconnected once the hard limit is reached, or if -# the soft limit is reached and remains reached for the specified number of -# seconds (continuously). -# So for instance if the hard limit is 32 megabytes and the soft limit is -# 16 megabytes / 10 seconds, the client will get disconnected immediately -# if the size of the output buffers reach 32 megabytes, but will also get -# disconnected if the client reaches 16 megabytes and continuously overcomes -# the limit for 10 seconds. -# -# By default normal clients are not limited because they don't receive data -# without asking (in a push way), but just after a request, so only -# asynchronous clients may create a scenario where data is requested faster -# than it can read. -# -# Instead there is a default limit for pubsub and replica clients, since -# subscribers and replicas receive data in a push fashion. -# -# Both the hard or the soft limit can be disabled by setting them to zero. -client-output-buffer-limit normal 0 0 0 -client-output-buffer-limit replica 256mb 64mb 60 -client-output-buffer-limit pubsub 32mb 8mb 60 - -# Client query buffers accumulate new commands. They are limited to a fixed -# amount by default in order to avoid that a protocol desynchronization (for -# instance due to a bug in the client) will lead to unbound memory usage in -# the query buffer. However you can configure it here if you have very special -# needs, such us huge multi/exec requests or alike. -# -# client-query-buffer-limit 1gb - -# In the Redis protocol, bulk requests, that are, elements representing single -# strings, are normally limited ot 512 mb. However you can change this limit -# here. -# -# proto-max-bulk-len 512mb - -# Redis calls an internal function to perform many background tasks, like -# closing connections of clients in timeout, purging expired keys that are -# never requested, and so forth. -# -# Not all tasks are performed with the same frequency, but Redis checks for -# tasks to perform according to the specified "hz" value. -# -# By default "hz" is set to 10. Raising the value will use more CPU when -# Redis is idle, but at the same time will make Redis more responsive when -# there are many keys expiring at the same time, and timeouts may be -# handled with more precision. -# -# The range is between 1 and 500, however a value over 100 is usually not -# a good idea. Most users should use the default of 10 and raise this up to -# 100 only in environments where very low latency is required. -hz 10 - -# Normally it is useful to have an HZ value which is proportional to the -# number of clients connected. This is useful in order, for instance, to -# avoid too many clients are processed for each background task invocation -# in order to avoid latency spikes. -# -# Since the default HZ value by default is conservatively set to 10, Redis -# offers, and enables by default, the ability to use an adaptive HZ value -# which will temporary raise when there are many connected clients. -# -# When dynamic HZ is enabled, the actual configured HZ will be used as -# as a baseline, but multiples of the configured HZ value will be actually -# used as needed once more clients are connected. In this way an idle -# instance will use very little CPU time while a busy instance will be -# more responsive. -dynamic-hz yes - -# When a child rewrites the AOF file, if the following option is enabled -# the file will be fsync-ed every 32 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -aof-rewrite-incremental-fsync yes - -# When redis saves RDB file, if the following option is enabled -# the file will be fsync-ed every 32 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -rdb-save-incremental-fsync yes - -# Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good -# idea to start with the default settings and only change them after investigating -# how to improve the performances and how the keys LFU change over time, which -# is possible to inspect via the OBJECT FREQ command. -# -# There are two tunable parameters in the Redis LFU implementation: the -# counter logarithm factor and the counter decay time. It is important to -# understand what the two parameters mean before changing them. -# -# The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis -# uses a probabilistic increment with logarithmic behavior. Given the value -# of the old counter, when a key is accessed, the counter is incremented in -# this way: -# -# 1. A random number R between 0 and 1 is extracted. -# 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1). -# 3. The counter is incremented only if R < P. -# -# The default lfu-log-factor is 10. This is a table of how the frequency -# counter changes with a different number of accesses with different -# logarithmic factors: -# -# +--------+------------+------------+------------+------------+------------+ -# | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | -# +--------+------------+------------+------------+------------+------------+ -# | 0 | 104 | 255 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 1 | 18 | 49 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 10 | 10 | 18 | 142 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 100 | 8 | 11 | 49 | 143 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# -# NOTE: The above table was obtained by running the following commands: -# -# redis-benchmark -n 1000000 incr foo -# redis-cli object freq foo -# -# NOTE 2: The counter initial value is 5 in order to give new objects a chance -# to accumulate hits. -# -# The counter decay time is the time, in minutes, that must elapse in order -# for the key counter to be divided by two (or decremented if it has a value -# less <= 10). -# -# The default value for the lfu-decay-time is 1. A Special value of 0 means to -# decay the counter every time it happens to be scanned. -# -# lfu-log-factor 10 -# lfu-decay-time 1 - -########################### ACTIVE DEFRAGMENTATION ####################### -# -# WARNING THIS FEATURE IS EXPERIMENTAL. However it was stress tested -# even in production and manually tested by multiple engineers for some -# time. -# -# What is active defragmentation? -# ------------------------------- -# -# Active (online) defragmentation allows a Redis server to compact the -# spaces left between small allocations and deallocations of data in memory, -# thus allowing to reclaim back memory. -# -# Fragmentation is a natural process that happens with every allocator (but -# less so with Jemalloc, fortunately) and certain workloads. Normally a server -# restart is needed in order to lower the fragmentation, or at least to flush -# away all the data and create it again. However thanks to this feature -# implemented by Oran Agra for Redis 4.0 this process can happen at runtime -# in an "hot" way, while the server is running. -# -# Basically when the fragmentation is over a certain level (see the -# configuration options below) Redis will start to create new copies of the -# values in contiguous memory regions by exploiting certain specific Jemalloc -# features (in order to understand if an allocation is causing fragmentation -# and to allocate it in a better place), and at the same time, will release the -# old copies of the data. This process, repeated incrementally for all the keys -# will cause the fragmentation to drop back to normal values. -# -# Important things to understand: -# -# 1. This feature is disabled by default, and only works if you compiled Redis -# to use the copy of Jemalloc we ship with the source code of Redis. -# This is the default with Linux builds. -# -# 2. You never need to enable this feature if you don't have fragmentation -# issues. -# -# 3. Once you experience fragmentation, you can enable this feature when -# needed with the command "CONFIG SET activedefrag yes". -# -# The configuration parameters are able to fine tune the behavior of the -# defragmentation process. If you are not sure about what they mean it is -# a good idea to leave the defaults untouched. - -# Enabled active defragmentation -# activedefrag yes - -# Minimum amount of fragmentation waste to start active defrag -# active-defrag-ignore-bytes 100mb - -# Minimum percentage of fragmentation to start active defrag -# active-defrag-threshold-lower 10 - -# Maximum percentage of fragmentation at which we use maximum effort -# active-defrag-threshold-upper 100 - -# Minimal effort for defrag in CPU percentage -# active-defrag-cycle-min 5 - -# Maximal effort for defrag in CPU percentage -# active-defrag-cycle-max 75 - -# Maximum number of set/hash/zset/list fields that will be processed from -# the main dictionary scan -# active-defrag-max-scan-fields 1000 - diff --git a/util/common/__init__.py b/util/common/__init__.py index 77895f8c0..395c72a29 100644 --- a/util/common/__init__.py +++ b/util/common/__init__.py @@ -1,4 +1,5 @@ +import functools import pprint import subprocess import sys @@ -35,6 +36,11 @@ def _execute(command,**kwargs): proc.wait() if check and proc.returncode != 0: + print("STDOUT:") + print(stdout) + print("STDERR (not interlaced properly, sorry):") + print(stderr) + raise subprocess.CalledProcessError( command, proc.returncode, @@ -53,32 +59,10 @@ def _docker(command, **kwargs): return _execute([ "docker-compose", "exec", '-T', - "files", + "site", ] + command, **kwargs) -def _status_single(server): - command = ['docker', 'container', 'inspect', '-f', '{{.State.Status}}', server] - result = _execute(command, check=False).stdout.strip() - return result - -# this should really be yanked out of the docker-compose somehow -_containers = ["themotte", "themotte_postgres", "themotte_redis"] - -def _all_running(): - for container in _containers: - if _status_single(container) != "running": - return False - - return True - -def _any_exited(): - for container in _containers: - if _status_single(container) == "exited": - return True - - return False - def _start(): print("Starting containers in operation mode . . .") print(" If this takes a while, it's probably building the container.") @@ -92,10 +76,26 @@ def _start(): ] result = _execute(command) - while not _all_running(): - if _any_exited(): - raise RuntimeError("Server exited prematurely") - time.sleep(1) + # alright this seems sketchy, bear with me + + # previous versions of this code used the '--wait' command-line flag + # the problem with --wait is that it waits for the container to be healthy and working + # "but wait, isn't that what we want?" + # ah, but see, if the container will *never* be healthy and working - say, if there's a flaw causing it to fail on startup - it just waits forever + # so that's not actually useful + + # previous versions of this code also had a check to see if the containers started up properly + # but this is surprisingly annoying to do if we don't know the containers' names + # docker-compose *can* do it, but you either have to use very new features that aren't supported on Ubuntu 22.04, or you have to go through a bunch of parsing pain + # and it kind of doesn't seem necessary + + # see, docker-compose in this form *will* wait until it's *attempted* to start each container. + # so at this point in execution, either the containers are running, or they're crashed + # if they're running, hey, problem solved, we're good + # if they're crashed, y'know what, problem still solved! because our next command will fail + + # maybe there's still a race condition? I dunno! Keep an eye on this. + # If there is a race condition then you're stuck doing something gnarly with `docker-compose ps`. Good luck! print(" Containers started!") @@ -106,7 +106,6 @@ def _stop(): command = ['docker-compose','stop'] print("Stopping containers . . .") result = _execute(command) - time.sleep(1) return result def _operation(name, commands):