You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [432e1450] nice Side A — unified diff (full patch): diff --git a/reddit.rs b/reddit.rs new file mode 100644 index 0000000000000000000000000000000000000000..da27f6f76482dd27d44cad9d7b844972bf042e64 --- /dev/null +++ b/reddit.rs @@ -0,0 +1,420 @@ +use governor::{Quota, RateLimiter, Jitter}; +use nonzero_ext::nonzero; +use reqwest::{Client, StatusCode}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; +use std::time::Duration; +use anyhow::{Result, Context, anyhow}; + +/// Reddit API client with built-in rate limiting +pub struct RedditClient { + client: Client, + limiter: Arc, + user_agent: String, +} + +impl RedditClient { + /// Create a new Reddit client with rate limiting + /// Reddit API allows 60 requests per minute for OAuth2 authenticated apps + /// We'll be conservative and use 50 requests per minute + pub fn new() -> Self { + // Create rate limiter: 50 requests per minute + let quota = Quota::per_minute(nonzero!(50u32)); + let limiter = Arc::new(RateLimiter::direct(quota)); + + // Create HTTP client with timeout + let client = Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .expect("Failed to create HTTP client"); + + // Reddit requires a unique user agent + let user_agent = format!( + "rust:sorter:v{} (by /u/hourLong_arnould)", + env!("CARGO_PKG_VERSION") + ); + + Self { + client, + limiter, + user_agent, + } + } + + /// Fetch hot posts from a subreddit + pub async fn get_subreddit_hot(&self, subreddit: &str, limit: usize) -> Result { + // Wait for rate limiter + self.limiter.until_ready_with_jitter(Jitter::up_to(Duration::from_millis(100))).await; + + let url = format!("https://www.reddit.com/r/{}/hot.json?limit={}", subreddit, limit); + + let response = self.client + .get(&url) + .header("User-Agent", &self.user_agent) + .send() + .await + .context("Failed to send request to Reddit")?; + + self.handle_response(response).await + } + + /// Fetch top posts from a subreddit + pub async fn get_subreddit_top(&self, subreddit: &str, limit: usize, time_period: &str) -> Result { + self.limiter.until_ready_with_jitter(Jitter::up_to(Duration::from_millis(100))).await; + + let url = format!( + "https://www.reddit.com/r/{}/top.json?limit={}&t={}", + subreddit, limit, time_period + ); + + let response = self.client + .get(&url) + .header("User-Agent", &self.user_agent) + .send() + .await + .context("Failed to send request to Reddit")?; + + self.handle_response(response).await + } + + /// Fetch new posts from a subreddit + pub async fn get_subreddit_new(&self, subreddit: &str, limit: usize) -> Result { + self.limiter.until_ready_with_jitter(Jitter::up_to(Duration::from_millis(100))).await; + + let url = format!("https://www.reddit.com/r/{}/new.json?limit={}", subreddit, limit); + + let response = self.client + .get(&url) + .header("User-Agent", &self.user_agent) + .send() + .await + .context("Failed to send request to Reddit")?; + + self.handle_response(response).await + } + + /// Fetch a specific post and its comments + pub async fn get_post(&self, subreddit: &str, post_id: &str) -> Result> { + self.limiter.until_ready_with_jitter(Jitter::up_to(Duration::from_millis(100))).await; + + let url = format!( + "https://www.reddit.com/r/{}/comments/{}.json", + subreddit, post_id + ); + + let response = self.client + .get(&url) + .header("User-Agent", &self.user_agent) + .send() + .await + .context("Failed to send request to Reddit")?; + + match response.status() { + StatusCode::OK => { + let listings: Vec = response + .json() + .await + .context("Failed to parse Reddit response")?; + Ok(listings) + } + StatusCode::TOO_MANY_REQUESTS => { + Err(anyhow!("Reddit rate limit exceeded. Please try again later.")) + } + StatusCode::NOT_FOUND => { + Err(anyhow!("Post not found: r/{}/comments/{}", subreddit, post_id)) + } + status => { + Err(anyhow!("Reddit API error: {}", status)) + } + } + } + + /// Fetch user profile (posts and comments) + pub async fn get_user_profile(&self, username: &str, content_type: &str, limit: usize) -> Result { + self.limiter.until_ready_with_jitter(Jitter::up_to(Duration::from_millis(100))).await; + + let url = format!( + "https://www.reddit.com/user/{}/{}.json?limit={}", + username, content_type, limit + ); + + let response = self.client + .get(&url) + .header("User-Agent", &self.user_agent) + .send() + .await + .context("Failed to send request to Reddit")?; + + self.handle_response(response).await + } + + /// Handle Reddit API response with proper error checking + async fn handle_response(&self, response: reqwest::Response) -> Result { + match response.status() { + StatusCode::OK => { + let listing: RedditListingResponse = response + .json() + .await + .context("Failed to parse Reddit response")?; + Ok(listing) + } + StatusCode::TOO_MANY_REQUESTS => { + Err(anyhow!("Reddit rate limit exceeded. Please try again later.")) + } + StatusCode::NOT_FOUND => { + Err(anyhow!("Reddit resource not found")) + } + StatusCode::FORBIDDEN => { + Err(anyhow!("Access forbidden. The subreddit may be private.")) + } + status => { + Err(anyhow!("Reddit API error: {}", status)) + } + } + } +} + +// Reddit API response types +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedditListingResponse { + pub kind: String, + pub data: RedditListingData, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedditListingData { + #[serde(skip_serializing_if = "Option::is_none")] + pub after: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub before: Option, + pub children: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub modhash: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedditThing { + pub kind: String, + pub data: RedditThingData, +} + +/// Reddit's "Thing" data can be either a post, comment, or other types +/// We use untagged enum to handle different data structures +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RedditThingData { + Post(RedditPost), + Comment(RedditComment), + // For things we don't care about yet (like "more" comments) + Other(serde_json::Value), +} + +/// Reddit post data with serde handling all the parsing +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedditPost { + pub id: String, + pub name: String, // Full name (t3_xxx) + #[serde(default = "default_untitled")] + pub title: String, + #[serde(default = "default_deleted_user")] + pub author: String, + pub subreddit: String, + #[serde(default)] + pub url: String, + #[serde(default)] + pub permalink: String, + #[serde(default, deserialize_with = "deserialize_selftext")] + pub selftext: Option, + #[serde(default)] + pub score: i64, + #[serde(default)] + pub num_comments: i64, + #[serde(default)] + pub created_utc: f64, + #[serde(default, deserialize_with = "deserialize_thumbnail")] + pub thumbnail: Option, + #[serde(default)] + pub is_video: bool, + #[serde(default)] + pub is_self: bool, + // Additional useful fields + #[serde(default)] + pub ups: i64, + #[serde(default)] + pub downs: i64, + #[serde(default)] + pub upvote_ratio: f64, + #[serde(default)] + pub over_18: bool, + #[serde(default)] + pub spoiler: bool, + #[serde(default)] + pub stickied: bool, + #[serde(default)] + pub locked: bool, + #[serde(default)] + pub distinguished: Option, +} + +/// Reddit comment data +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RedditComment { + pub id: String, + pub name: String, // Full name (t1_xxx) + #[serde(default = "default_deleted_user")] + pub author: String, + #[serde(default)] + pub body: String, + #[serde(default)] + pub score: i64, + #[serde(default)] + pub created_utc: f64, + #[serde(default)] + pub parent_id: String, + #[serde(default)] + pub permalink: String, + #[serde(default)] + pub depth: i32, + // Additional useful fields + #[serde(default)] + pub ups: i64, + #[serde(default)] + pub downs: i64, + #[serde(default)] + pub edited: RedditEditStatus, + #[serde(default)] + pub stickied: bool, + #[serde(default)] + pub distinguished: Option, + #[serde(default)] + pub is_submitter: bool, + #[serde(default)] + pub collapsed: bool, + #[serde(default)] + pub controversiality: i32, +} + +/// Reddit's edit status - can be false or a timestamp +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RedditEditStatus { + NotEdited(bool), + EditedAt(f64), +} + +impl Default for RedditEditStatus { + fn default() -> Self { + RedditEditStatus::NotEdited(false) + } +} + +// Helper functions for serde defaults +fn default_untitled() -> String { + "Untitled".to_string() +} + +fn default_deleted_user() -> String { + "[deleted]".to_string() +} + +// Custom deserializer for selftext (empty strings should be None) +fn deserialize_selftext<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s: Option = Option::deserialize(deserializer)?; + Ok(s.filter(|text| !text.is_empty())) +} + +// Custom deserializer for thumbnail (filter out "self", "default", empty) +fn deserialize_thumbnail<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let s: Option = Option::deserialize(deserializer)?; + Ok(s.filter(|thumb| { + !thumb.is_empty() && thumb != "self" && thumb != "default" && thumb != "nsfw" && thumb != "spoiler" + })) +} + +// Helper methods for extracting typed data from Things +impl RedditThing { + /// Try to get this Thing as a Post + pub fn as_post(&self) -> Option<&RedditPost> { + if self.kind != "t3" { + return None; + } + match &self.data { + RedditThingData::Post(post) => Some(post), + _ => None, + } + } + + /// Try to get this Thing as a Comment + pub fn as_comment(&self) -> Option<&RedditComment> { + if self.kind != "t1" { + return None; + } + match &self.data { + RedditThingData::Comment(comment) => Some(comment), + _ => None, + } + } + + /// Check if this is a "more comments" indicator + pub fn is_more_comments(&self) -> bool { + self.kind == "more" + } +} + +// Helper methods for working with listing responses +impl RedditListingResponse { + /// Extract all posts from this listing + pub fn get_posts(&self) -> Vec<&RedditPost> { + self.data.children.iter() + .filter_map(|thing| thing.as_post()) + .collect() + } + + /// Extract all comments from this listing + pub fn get_comments(&self) -> Vec<&RedditComment> { + self.data.children.iter() + .filter_map(|thing| thing.as_comment()) + .collect() + } + + /// Extract posts as owned values + pub fn into_posts(self) -> Vec { + self.data.children.into_iter() + .filter_map(|thing| { + if thing.kind == "t3" { + match thing.data { + RedditThingData::Post(post) => Some(post), + _ => None, + } + } else { + None + } + }) + .collect() + } + + /// Extract comments as owned values + pub fn into_comments(self) -> Vec { + self.data.children.into_iter() + .filter_map(|thing| { + if thing.kind == "t1" { + match thing.data { + RedditThingData::Comment(comment) => Some(comment), + _ => None, + } + } else { + None + } + }) + .collect() + } +} + + + Side B — contributor: tommy-mor Side B — commit message: [6120bd96] fix redirect urls for custom hosts and deploy from staging Use HOSTNAME and window.location.origin instead of hardcoded staging.sorter.social, and trigger fly deploys on pushes to staging. Co-authored-by: Cursor Side B — unified diff (full patch): diff --git a/.github/workflows/fly-deploy.yml b/.github/workflows/fly-deploy.yml index 3e693915fe6f99a5c2221b2921bf8ebc305180fc..5e11e5c312f62bed34d8cc68bd4a5538f52476b9 100644 --- a/.github/workflows/fly-deploy.yml +++ b/.github/workflows/fly-deploy.yml @@ -3,11 +3,11 @@ name: deploy to fly.io on: push: branches: - - main + - staging workflow_dispatch: concurrency: - group: fly-deploy-main + group: fly-deploy-staging cancel-in-progress: true jobs: diff --git a/borter/src/app/linear.clj b/borter/src/app/linear.clj index f77d8a974e0cf05f9c33233bb625bdb190d2007b..5ef0e34cf1d543826675c6facb66aec079b40561 100644 --- a/borter/src/app/linear.clj +++ b/borter/src/app/linear.clj @@ -6,6 +6,7 @@ [ring.util.response :as response] [app.database :as db] [app.permissions :as perms] + [app.util :as util] [honey.sql.helpers :as h] [sluj.core :refer [sluj]])) @@ -13,9 +14,7 @@ (def client-secret (System/getenv "BORTER_LINEAR_CLIENT_SECRET")) (defn get-hostname [] - (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost)) - "sorter.social" "https://sorter.social/api/linear/callback" - "http://localhost:3000/api/linear/callback")) + (str (util/get-base-url) "/api/linear/callback")) (defn code->token [code] (def code code) diff --git a/borter/src/app/login.clj b/borter/src/app/login.clj index 5d545db9bef7765ba8b3fe7d00261c8ce84e9e1a..86817f8e94bc174e5b108859cc0b342953ab7acb 100644 --- a/borter/src/app/login.clj +++ b/borter/src/app/login.clj @@ -1,6 +1,7 @@ (ns app.login (:require [crypto.password.bcrypt :as password] [app.database :as db] + [app.util :as util] [honey.sql.helpers :as h] [hato.client :as hc] [clojure.data.json :as json] @@ -12,10 +13,7 @@ (def environment (or (System/getenv "ENVIRONMENT") "development")) (defn get-base-url [] - (case environment - "production" "https://sorter.social" - "staging" "https://staging.sorter.social" - "development" "http://localhost:3000")) ; fallback for development + (util/get-base-url)) (defn create-email-content "Creates a standardized email structure with customizable content" diff --git a/borter/src/app/oauth.clj b/borter/src/app/oauth.clj index 1166f2ee30c9e813840711c72d1ad8f1c62e1ffe..2cd0c62f1fe267f7f5f725a97bc3ba0d0889517f 100644 --- a/borter/src/app/oauth.clj +++ b/borter/src/app/oauth.clj @@ -3,6 +3,7 @@ [clojure.data.json :as json] [hato.client :as hc] [app.database :as db] + [app.util :as util] [honey.sql.helpers :as h] [ring.util.codec :as codec]) (:import [java.util Base64])) @@ -13,12 +14,7 @@ encoded-bytes)) (defn get-hostname [] - (let [env (System/getenv "ENVIRONMENT")] - (println "Current environment:" env) - (case env - "production" "https://sorter.social" - "staging" "https://staging.sorter.social" - "http://localhost:3000"))) + (util/get-base-url)) (defn get-origin-hostname [req] (let [origin (get-in req [:headers "origin"]) diff --git a/borter/src/app/spotify.clj b/borter/src/app/spotify.clj index 3e11713119141812fa2707ec956fb7ed612ee69a..b38d734351a1d4f1e142d93d4435ffe7bd20c02d 100644 --- a/borter/src/app/spotify.clj +++ b/borter/src/app/spotify.clj @@ -1,5 +1,6 @@ (ns app.spotify (:require [app.oauth :as oauth] + [app.util :as util] [hato.client :as hc] [clojure.data.json :as json] [ring.util.codec :as codec] @@ -47,10 +48,7 @@ (defn get-hostname [] - (case (System/getenv "ENVIRONMENT") - "production" "https://sorter.social" - "staging" "https://staging.sorter.social" - "http://localhost:3000")) + (util/get-base-url)) (defn create-spotify-tag "Creates a tag for a Spotify entity (artist, album, track) if it doesn't exist" diff --git a/borter/src/app/twitter.clj b/borter/src/app/twitter.clj index ef7b18fa1fcb82bb944b3035ffed44499181237f..b9a3fdccc15d13918a4d11d8c0443de94fd172b4 100644 --- a/borter/src/app/twitter.clj +++ b/borter/src/app/twitter.clj @@ -1,6 +1,7 @@ (ns app.twitter (:require [app.database :as db] [app.permissions :as perms] + [app.util :as util] [honey.sql.helpers :as h] [hato.client :as hc] [clojure.data.json :as json] @@ -37,9 +38,7 @@ (clojure.string/join "&" (map (fn [[k v]] (str (name k) "=" v)) params))) (defn get-hostname [] - (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost)) - "sorter.isnt.online" "https://sorter.isnt.online/api/twitter/callback" - "http://localhost:3000/api/twitter/callback")) + (str (util/get-base-url) "/api/twitter/callback")) (defn encode-b64 [s] (.encodeToString (java.util.Base64/getEncoder) (.getBytes s))) diff --git a/borter/src/app/util.clj b/borter/src/app/util.clj index 384a64306c84aa8288ec44cd5de57edc248a826d..6a8aa0875accb28dc81bf57e645e3961b0a3ace5 100644 --- a/borter/src/app/util.clj +++ b/borter/src/app/util.clj @@ -2,6 +2,18 @@ (:require [clojure.string :as string]) (:import [java.net URLEncoder])) +(defn get-base-url + "Public site base URL for redirects and oauth callbacks." + [] + (if-let [hostname (not-empty (System/getenv "HOSTNAME"))] + (if (string/starts-with? hostname "http") + (string/replace hostname #"/$" "") + (str "https://" (string/replace hostname #"/$" ""))) + (case (or (System/getenv "ENVIRONMENT") "development") + "production" "https://sorter.social" + "staging" "https://staging.sorter.social" + "http://localhost:3000"))) + (defn urlencode-params [params] (clojure.string/join "&" (map (fn [[k v]] (str k "=" (URLEncoder/encode (str v) "UTF-8"))) params))) diff --git a/borter/src/app/youtube.clj b/borter/src/app/youtube.clj index 647ef7c6d4f2503a63a7c074d46dc815b2a23547..fc9a2f5ed516692f19e06b4c0221f510547cf8c0 100644 --- a/borter/src/app/youtube.clj +++ b/borter/src/app/youtube.clj @@ -6,6 +6,7 @@ [ring.util.response :as response] [app.database :as db] [app.permissions :as perms] + [app.util :as util] [honey.sql.helpers :as h] [sluj.core :refer [sluj]])) @@ -32,9 +33,7 @@ :body (json/read-str {:key-fn keyword}))) (defn get-hostname [] - (case (.getCanonicalHostName (java.net.InetAddress/getLocalHost)) - "localhost" "http://localhost:3000/api/youtube/callback" - "https://sorter.isnt.online/api/youtube/callback")) + (str (util/get-base-url) "/api/youtube/callback")) diff --git a/forter/src/utils/authUtils.js b/forter/src/utils/authUtils.js index 145e5db7ad6f7a6439d68c63beb4d07d31b2de08..98ed7fa671f9887f44dc1479d85569951eb4773e 100644 --- a/forter/src/utils/authUtils.js +++ b/forter/src/utils/authUtils.js @@ -5,8 +5,11 @@ import { current_session, fetchSession } from "../session"; let lastSyncTime = 0; const SYNC_THROTTLE_MS = 5000; // Only sync once every 5 seconds -// Get base URL based on Vite's mode +// Get base URL based on current origin, with build-mode fallbacks for SSR/build const getBaseUrl = () => { + if (typeof window !== 'undefined' && window.location?.origin) { + return window.location.origin; + } switch (import.meta.env.MODE) { case 'production': return 'https://sorter.social';