mirror of
https://github.com/httpjamesm/AnonymousOverflow.git
synced 2024-12-06 19:16:43 +01:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 86c8899576 |
@@ -23,7 +23,7 @@ tmp_dir = "tmp"
|
||||
rerun = false
|
||||
rerun_delay = 500
|
||||
send_interrupt = false
|
||||
stop_on_error = true
|
||||
stop_on_error = false
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
name: Create and publish a Docker image
|
||||
|
||||
# Configures this workflow to run every time a change is pushed to the branch called `release`.
|
||||
on:
|
||||
push:
|
||||
branches: ['release']
|
||||
|
||||
# Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
# There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu.
|
||||
jobs:
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
# Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job.
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
#
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
# Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
# This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels.
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
# This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages.
|
||||
# It uses the `context` parameter to define the build's context as the set of files located in the specified path. For more information, see "[Usage](https://github.com/docker/build-push-action#usage)" in the README of the `docker/build-push-action` repository.
|
||||
# It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step.
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.22.1-alpine3.19 as build
|
||||
FROM golang:1.19-alpine as build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -6,52 +6,46 @@ This project is super lightweight by design. The UI is simple and the frontend i
|
||||
|
||||
## Screenshots
|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||

|
||||

|
||||
|
||||
## Clearnet Instances
|
||||
|
||||
| Instance URL | Region | Notes |
|
||||
| ----------------------------------------------------------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| [code.whatever.social](https://code.whatever.social) | Germany | Operated by [Whatever Social](https://whatever.social) and [http.james](https://httpjames.space) |
|
||||
| [ao.vern.cc](https://ao.vern.cc) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [overflow.smnz.de](https://overflow.smnz.de) | Germany | Operated by [smnz.de](https://smnz.de) |
|
||||
| [overflow.lunar.icu](https://overflow.lunar.icu) | Germany | Operated by [lunar.icu](https://lunar.icu/) |
|
||||
| [overflow.adminforge.de](https://overflow.adminforge.de/) | Germany | Operated by [adminForge](https://adminforge.de/) |
|
||||
| [overflow.hostux.net](https://overflow.hostux.net/) | France | Operated by [Hostux](https://hostux.net/) |
|
||||
| [overflow.projectsegfau.lt](https://overflow.projectsegfau.lt/) | United States, France, India | Operated by [Project Segfault](https://projectsegfau.lt/) |
|
||||
| [code.xbdm.fun](https://code.xbdm.fun) | Germany | Operated by [xbdm.fun](https://xbdm.fun) |
|
||||
| [overflow.fascinated.cc](https://overflow.fascinated.cc/) | Germany | Operated by [fascinated.cc](https://fascinated.cc/) |
|
||||
| [ao.bloat.cat](https://ao.bloat.cat) | Romania | Operated by [bloatcat.tk](https://bloat.cat) |
|
||||
| [anonoverflow.frontendfriendly.xyz](https://anonoverflow.frontendfriendly.xyz/) | United States | Operated by [frontendfriendly.xyz](https://frontendfriendly.xyz/) |
|
||||
| [ao.owo.si](https://ao.owo.si/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
| [overflow.datura.network](https://overflow.datura.network/) | Germany | Operated by [datura.network](https://datura.network) |
|
||||
| [overflow.freedit.eu](overflow.freedit.eu) | United States | Operated by [freedit.eu](https://freedit.eu) |
|
||||
| [ao.ftw.lol](https://ao.ftw.lol) | Germany | Operated by [ftw.lol](https://ftw.lol) |
|
||||
| [anonoverflow.hyperreal.coffee](https://anonoverflow.hyperreal.coffee) | United States | Operated by [hyperreal.coffee](https://hyperreal.coffee) |
|
||||
| [a.opnxng.com](a.opnxng.com) | Singapore | Operated by [opnxng.com](https://about.opnxng.com) |
|
||||
| [overflow.sudovanilla.com](https://overflow.sudovanilla.com) | United States | Operated by [SudoVanilla](https://sudovanilla.com) |
|
||||
| [anonymousoverflow.privacyfucking.rocks](https://anonymousoverflow.privacyfucking.rocks/) | Germany | Operated by [privacyfucking.rocks](https://privacyfucking.rocks) |
|
||||
| [exchange.seitan-ayoub.lol](https://exchange.seitan-ayoub.lol) | Germany | Operated by [Seitan Ayoub](https://seitan-ayoub.lol) |
|
||||
| [overflow.r4fo.com](https://overflow.r4fo.com) | The Netherlands | Operated by [r4fo.com](https://r4fo.com) |
|
||||
| [overflow.ducks.party](https://overflow.ducks.party) | The Netherlands | Operated by [ducks.party](https://ducks.party) |
|
||||
| [ao.ngn.tf](https://ao.ngn.tf) | Turkey | Operated by [ngn](https://ngn.tf) |
|
||||
| [overflow.snine.nl](https://overflow.snine.nl) | The Netherlands | Operated by [snine](https://snine.nl) |
|
||||
| Instance URL | Region | Notes |
|
||||
| ------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| [code.whatever.social](https://code.whatever.social) | United States & The Netherlands | Operated by [Whatever Social](https://whatever.social) and [http.james](https://httpjames.space) |
|
||||
| [ao.vern.cc](https://ao.vern.cc) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [overflow.smnz.de](https://overflow.smnz.de) | Germany | Operated by [smnz.de](https://smnz.de) |
|
||||
| [overflow.lunar.icu](https://overflow.lunar.icu) | Germany | Operated by [lunar.icu](https://lunar.icu/) |
|
||||
| [overflow.adminforge.de](https://overflow.adminforge.de/) | Germany | Operated by [adminForge](https://adminforge.de/) |
|
||||
| [overflow.hostux.net](https://overflow.hostux.net/) | France | Operated by [Hostux](https://hostux.net/) |
|
||||
| [overflow.projectsegfau.lt](https://overflow.projectsegfau.lt/) | United States, France, India | Operated by [Project Segfault](https://projectsegfau.lt/) |
|
||||
| [code.xbdm.fun](https://code.xbdm.fun) | Germany | Operated by [xbdm.fun](https://xbdm.fun) |
|
||||
| [overflow.fascinated.cc](https://overflow.fascinated.cc/) | Germany | Operated by [fascinated.cc](https://fascinated.cc/) |
|
||||
| [ao.bloatcat.tk](https://ao.bloatcat.tk) | Iceland | Operated by [bloatcat.tk](https://bloatcat.tk) |
|
||||
| [anonoverflow.frontendfriendly.xyz](https://anonoverflow.frontendfriendly.xyz/) | United States | Operated by [frontendfriendly.xyz](https://frontendfriendly.xyz/) |
|
||||
| [ao.owo.si](https://ao.owo.si/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
| [overflow.datura.network](https://overflow.datura.network/) | Germany | Operated by [datura.network](https://datura.network) |
|
||||
| [overflow.freedit.eu](overflow.freedit.eu) | United States | Operated by [freedit.eu](https://freedit.eu) |
|
||||
| [ao.ftw.lol](https://ao.ftw.lol) | Germany | Operated by [ftw.lol](https://ftw.lol) |
|
||||
| [anonoverflow.hyperreal.coffee](https://anonoverflow.hyperreal.coffee) | United States | Operated by [hyperreal.coffee](https://hyperreal.coffee) |
|
||||
| [a.opnxng.com](a.opnxng.com) | Singapore | Operated by [opnxng.com](https://about.opnxng.com) |
|
||||
| [overflow.sudovanilla.com](https://overflow.sudovanilla.com) | United States | Operated by [SudoVanilla](https://sudovanilla.com)|
|
||||
|
||||
|
||||
## Other Instances
|
||||
|
||||
| Instance URL | Region | Notes |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | --------------------------------------------------------- |
|
||||
| [ao.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad.onion](http://ao.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad.onion) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [vernmzgraj6aaoafmehupvtkkynpaa67rxcdj2kinwiy6konn6rq.b32.i2p](http://vernmzgraj6aaoafmehupvtkkynpaa67rxcdj2kinwiy6konn6rq.b32.i2p) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [overflow.pjsfkvpxlinjamtawaksbnnaqs2fc2mtvmozrzckxh7f3kis6yea25ad.onion](http://overflow.pjsfkvpxlinjamtawaksbnnaqs2fc2mtvmozrzckxh7f3kis6yea25ad.onion/) | Luxembourg | Operated by [Project Segfault](https://projectsegfau.lt/) |
|
||||
| [overflow.daturab6drmkhyeia4ch5gvfc2f3wgo6bhjrv3pz6n7kxmvoznlkq4yd.onion](http://overflow.daturab6drmkhyeia4ch5gvfc2f3wgo6bhjrv3pz6n7kxmvoznlkq4yd.onion/) | Germany | Operated by [datura.network](https://datura.network) |
|
||||
| [ao.pk47sgwhncn5cgidm7bofngmh7lc7ukjdpk5bjwfemmyp27ovl25ikyd.onion](http://ao.pk47sgwhncn5cgidm7bofngmh7lc7ukjdpk5bjwfemmyp27ovl25ikyd.onion/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
| [ay7akchgdh76r4lc62hzd52z6xqoh67loototsetvqxo5o7ngo5q.b32.i2p](http://ay7akchgdh76r4lc62hzd52z6xqoh67loototsetvqxo5o7ngo5q.b32.i2p/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
| [overflow.r4focoma7gu2zdwwcjjad47ysxt634lg73sxmdbkdozanwqslho5ohyd.onion](http://overflow.r4focoma7gu2zdwwcjjad47ysxt634lg73sxmdbkdozanwqslho5ohyd.onion) | The Netherlands | Operated by [r4fo.com](https://r4fo.com) |
|
||||
| Instance URL | Region | Notes |
|
||||
| ---------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | --------------------------------------------------------- |
|
||||
| [ao.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad.onion](http://ao.vernccvbvyi5qhfzyqengccj7lkove6bjot2xhh5kajhwvidqafczrad.onion) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [vernmzgraj6aaoafmehupvtkkynpaa67rxcdj2kinwiy6konn6rq.b32.i2p](http://vernmzgraj6aaoafmehupvtkkynpaa67rxcdj2kinwiy6konn6rq.b32.i2p) | United States | Operated by [vern.cc](https://vern.cc) |
|
||||
| [overflow.pjsfkvpxlinjamtawaksbnnaqs2fc2mtvmozrzckxh7f3kis6yea25ad.onion](http://overflow.pjsfkvpxlinjamtawaksbnnaqs2fc2mtvmozrzckxh7f3kis6yea25ad.onion/) | Luxembourg | Operated by [Project Segfault](https://projectsegfau.lt/) |
|
||||
| [overflow.daturab6drmkhyeia4ch5gvfc2f3wgo6bhjrv3pz6n7kxmvoznlkq4yd.onion](http://overflow.daturab6drmkhyeia4ch5gvfc2f3wgo6bhjrv3pz6n7kxmvoznlkq4yd.onion/) | Germany | Operated by [datura.network](https://datura.network) |
|
||||
| [ao.pk47sgwhncn5cgidm7bofngmh7lc7ukjdpk5bjwfemmyp27ovl25ikyd.onion](http://ao.pk47sgwhncn5cgidm7bofngmh7lc7ukjdpk5bjwfemmyp27ovl25ikyd.onion/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
| [ay7akchgdh76r4lc62hzd52z6xqoh67loototsetvqxo5o7ngo5q.b32.i2p](http://ay7akchgdh76r4lc62hzd52z6xqoh67loototsetvqxo5o7ngo5q.b32.i2p/) | Germany | Operated by [owo.si](https://owo.si/) |
|
||||
|
||||
## Why use AnonymousOverflow over StackOverflow?
|
||||
|
||||
@@ -127,4 +121,3 @@ Read the [wiki page](https://github.com/httpjamesm/AnonymousOverflow/wiki/Deploy
|
||||
- [goquery](https://github.com/PuerkitoBio/goquery) under the [BSD 3-Clause License](https://github.com/PuerkitoBio/goquery/blob/master/LICENSE)
|
||||
- [resty](https://github.com/go-resty/resty) under the [MIT License](https://github.com/go-resty/resty/blob/master/LICENSE)
|
||||
- [Chroma](https://github.com/alecthomas/chroma) under the [MIT License](https://github.com/alecthomas/chroma/blob/master/COPYING)
|
||||
- [KaTeX](https://github.com/KaTeX/KaTeX) under the [MIT License](https://github.com/KaTeX/KaTeX/blob/main/LICENSE)
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
package config
|
||||
|
||||
var Version = "1.12.0"
|
||||
var Version = "1.9.0"
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
anonymousoverflow:
|
||||
container_name: 'app'
|
||||
image: 'ghcr.io/httpjamesm/anonymousoverflow:release'
|
||||
environment:
|
||||
- APP_URL=https://domain.com
|
||||
- JWT_SIGNING_SECRET=secret
|
||||
ports:
|
||||
- '80:8080'
|
||||
restart: 'always'
|
||||
anonymousoverflow:
|
||||
container_name: 'app'
|
||||
build:
|
||||
context: .
|
||||
network: 'host'
|
||||
environment:
|
||||
- APP_URL=https://domain.com
|
||||
- JWT_SIGNING_SECRET=secret
|
||||
ports:
|
||||
- '80:8080'
|
||||
restart: 'always'
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 59 KiB |
@@ -13,7 +13,6 @@ require (
|
||||
|
||||
require (
|
||||
github.com/andybalholm/cascadia v1.3.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dlclark/regexp2 v1.7.0 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.0 // indirect
|
||||
@@ -26,8 +25,6 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
github.com/ugorji/go/codec v1.2.8 // indirect
|
||||
golang.org/x/crypto v0.4.0 // indirect
|
||||
golang.org/x/net v0.7.0 // indirect
|
||||
@@ -35,5 +32,4 @@ require (
|
||||
golang.org/x/text v0.7.0 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -72,8 +72,6 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/ugorji/go/codec v1.2.8 h1:sgBJS6COt0b/P40VouWKdseidkDgHxYGm0SAglUHfP0=
|
||||
github.com/ugorji/go/codec v1.2.8/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
|
||||
@@ -51,8 +51,6 @@ func main() {
|
||||
r.POST("/", routes.PostHome)
|
||||
|
||||
r.GET("/a/:id", routes.RedirectShortenedOverflowURL)
|
||||
r.GET("/q/:id", routes.RedirectShortenedOverflowURL)
|
||||
r.GET("/q/:id/:answerId", routes.RedirectShortenedOverflowURL)
|
||||
|
||||
r.GET("/questions/:id", func(c *gin.Context) {
|
||||
// redirect user to the question with the title
|
||||
|
||||
@@ -50,15 +50,3 @@ html {
|
||||
details {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.d-flex {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.fd-column {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.fw-nowrap {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
<h1><a href="https://katex.org/">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://katex.org/img/katex-logo.svg">
|
||||
<img alt="KaTeX" width=130 src="https://katex.org/img/katex-logo-black.svg">
|
||||
</picture>
|
||||
</a></h1>
|
||||
|
||||
[](https://www.npmjs.com/package/katex)
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
[](https://github.com/KaTeX/KaTeX/actions?query=workflow%3ACI)
|
||||
[](https://codecov.io/gh/KaTeX/KaTeX)
|
||||
[](https://github.com/KaTeX/KaTeX/discussions)
|
||||
[](https://www.jsdelivr.com/package/npm/katex)
|
||||

|
||||
[](https://gitpod.io/#https://github.com/KaTeX/KaTeX)
|
||||
[](https://opencollective.com/katex)
|
||||
|
||||
KaTeX is a fast, easy-to-use JavaScript library for TeX math rendering on the web.
|
||||
|
||||
* **Fast:** KaTeX renders its math synchronously and doesn't need to reflow the page. See how it compares to a competitor in [this speed test](https://www.intmath.com/cg5/katex-mathjax-comparison.php).
|
||||
* **Print quality:** KaTeX's layout is based on Donald Knuth's TeX, the gold standard for math typesetting.
|
||||
* **Self contained:** KaTeX has no dependencies and can easily be bundled with your website resources.
|
||||
* **Server side rendering:** KaTeX produces the same output regardless of browser or environment, so you can pre-render expressions using Node.js and send them as plain HTML.
|
||||
|
||||
KaTeX is compatible with all major browsers, including Chrome, Safari, Firefox, Opera, Edge, and IE 11.
|
||||
|
||||
KaTeX supports much (but not all) of LaTeX and many LaTeX packages. See the [list of supported functions](https://katex.org/docs/supported.html).
|
||||
|
||||
Try out KaTeX [on the demo page](https://katex.org/#demo)!
|
||||
|
||||
## Getting started
|
||||
|
||||
### Starter template
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<!-- KaTeX requires the use of the HTML5 doctype. Without it, KaTeX may not render properly -->
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous">
|
||||
|
||||
<!-- The loading of KaTeX is deferred to speed up page rendering -->
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.js" integrity="sha384-cpW21h6RZv/phavutF+AuVYrr+dA8xD9zs6FwLpaCct6O9ctzYFfFr4dgmgccOTx" crossorigin="anonymous"></script>
|
||||
|
||||
<!-- To automatically render math in text elements, include the auto-render extension: -->
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/contrib/auto-render.min.js" integrity="sha384-+VBxd3r6XgURycqtZ117nYw44OOcIax56Z4dCRWbxyPt0Koah1uHoK0o4+/RRE05" crossorigin="anonymous"
|
||||
onload="renderMathInElement(document.body);"></script>
|
||||
</head>
|
||||
...
|
||||
</html>
|
||||
```
|
||||
|
||||
You can also [download KaTeX](https://github.com/KaTeX/KaTeX/releases) and host it yourself.
|
||||
|
||||
For details on how to configure auto-render extension, refer to [the documentation](https://katex.org/docs/autorender.html).
|
||||
|
||||
### API
|
||||
|
||||
Call `katex.render` to render a TeX expression directly into a DOM element.
|
||||
For example:
|
||||
|
||||
```js
|
||||
katex.render("c = \\pm\\sqrt{a^2 + b^2}", element, {
|
||||
throwOnError: false
|
||||
});
|
||||
```
|
||||
|
||||
Call `katex.renderToString` to generate an HTML string of the rendered math,
|
||||
e.g., for server-side rendering. For example:
|
||||
|
||||
```js
|
||||
var html = katex.renderToString("c = \\pm\\sqrt{a^2 + b^2}", {
|
||||
throwOnError: false
|
||||
});
|
||||
// '<span class="katex">...</span>'
|
||||
```
|
||||
|
||||
Make sure to include the CSS and font files in both cases.
|
||||
If you are doing all rendering on the server, there is no need to include the
|
||||
JavaScript on the client.
|
||||
|
||||
The examples above use the `throwOnError: false` option, which renders invalid
|
||||
inputs as the TeX source code in red (by default), with the error message as
|
||||
hover text. For other available options, see the
|
||||
[API documentation](https://katex.org/docs/api.html),
|
||||
[options documentation](https://katex.org/docs/options.html), and
|
||||
[handling errors documentation](https://katex.org/docs/error.html).
|
||||
|
||||
## Demo and Documentation
|
||||
|
||||
Learn more about using KaTeX [on the website](https://katex.org)!
|
||||
|
||||
## Contributors
|
||||
|
||||
### Code Contributors
|
||||
|
||||
This project exists thanks to all the people who contribute code. If you'd like to help, see [our guide to contributing code](CONTRIBUTING.md).
|
||||
<a href="https://github.com/KaTeX/KaTeX/graphs/contributors"><img src="https://contributors-svg.opencollective.com/katex/contributors.svg?width=890&button=false" alt="Code contributors" /></a>
|
||||
|
||||
### Financial Contributors
|
||||
|
||||
Become a financial contributor and help us sustain our community.
|
||||
|
||||
#### Individuals
|
||||
|
||||
<a href="https://opencollective.com/katex"><img src="https://opencollective.com/katex/individuals.svg?width=890" alt="Contribute on Open Collective"></a>
|
||||
|
||||
#### Organizations
|
||||
|
||||
Support this project with your organization. Your logo will show up here with a link to your website.
|
||||
|
||||
<a href="https://opencollective.com/katex/organization/0/website"><img src="https://opencollective.com/katex/organization/0/avatar.svg" alt="Organization 1"></a>
|
||||
<a href="https://opencollective.com/katex/organization/1/website"><img src="https://opencollective.com/katex/organization/1/avatar.svg" alt="Organization 2"></a>
|
||||
<a href="https://opencollective.com/katex/organization/2/website"><img src="https://opencollective.com/katex/organization/2/avatar.svg" alt="Organization 3"></a>
|
||||
<a href="https://opencollective.com/katex/organization/3/website"><img src="https://opencollective.com/katex/organization/3/avatar.svg" alt="Organization 4"></a>
|
||||
<a href="https://opencollective.com/katex/organization/4/website"><img src="https://opencollective.com/katex/organization/4/avatar.svg" alt="Organization 5"></a>
|
||||
<a href="https://opencollective.com/katex/organization/5/website"><img src="https://opencollective.com/katex/organization/5/avatar.svg" alt="Organization 6"></a>
|
||||
<a href="https://opencollective.com/katex/organization/6/website"><img src="https://opencollective.com/katex/organization/6/avatar.svg" alt="Organization 7"></a>
|
||||
<a href="https://opencollective.com/katex/organization/7/website"><img src="https://opencollective.com/katex/organization/7/avatar.svg" alt="Organization 8"></a>
|
||||
<a href="https://opencollective.com/katex/organization/8/website"><img src="https://opencollective.com/katex/organization/8/avatar.svg" alt="Organization 9"></a>
|
||||
<a href="https://opencollective.com/katex/organization/9/website"><img src="https://opencollective.com/katex/organization/9/avatar.svg" alt="Organization 10"></a>
|
||||
|
||||
## License
|
||||
|
||||
KaTeX is licensed under the [MIT License](https://opensource.org/licenses/MIT).
|
||||
-1
@@ -1 +0,0 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("katex")):"function"==typeof define&&define.amd?define(["katex"],t):"object"==typeof exports?exports.renderMathInElement=t(require("katex")):e.renderMathInElement=t(e.katex)}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={771:function(t){t.exports=e}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var a=r[e]={exports:{}};return t[e](a,a.exports,n),a.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var i={};return function(){n.d(i,{default:function(){return s}});var e=n(771),t=n.n(e),r=function(e,t,r){for(var n=r,i=0,a=e.length;n<t.length;){var o=t[n];if(i<=0&&t.slice(n,n+a)===e)return n;"\\"===o?n++:"{"===o?i++:"}"===o&&i--,n++}return-1},a=/^\\begin{/,o=function(e,t){for(var n,i=[],o=new RegExp("("+t.map((function(e){return e.left.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")})).join("|")+")");-1!==(n=e.search(o));){n>0&&(i.push({type:"text",data:e.slice(0,n)}),e=e.slice(n));var l=t.findIndex((function(t){return e.startsWith(t.left)}));if(-1===(n=r(t[l].right,e,t[l].left.length)))break;var d=e.slice(0,n+t[l].right.length),s=a.test(d)?d:e.slice(t[l].left.length,n);i.push({type:"math",data:s,rawData:d,display:t[l].display}),e=e.slice(n+t[l].right.length)}return""!==e&&i.push({type:"text",data:e}),i},l=function(e,r){var n=o(e,r.delimiters);if(1===n.length&&"text"===n[0].type)return null;for(var i=document.createDocumentFragment(),a=0;a<n.length;a++)if("text"===n[a].type)i.appendChild(document.createTextNode(n[a].data));else{var l=document.createElement("span"),d=n[a].data;r.displayMode=n[a].display;try{r.preProcess&&(d=r.preProcess(d)),t().render(d,l,r)}catch(e){if(!(e instanceof t().ParseError))throw e;r.errorCallback("KaTeX auto-render: Failed to parse `"+n[a].data+"` with ",e),i.appendChild(document.createTextNode(n[a].rawData));continue}i.appendChild(l)}return i},d=function e(t,r){for(var n=0;n<t.childNodes.length;n++){var i=t.childNodes[n];if(3===i.nodeType){for(var a=i.textContent,o=i.nextSibling,d=0;o&&o.nodeType===Node.TEXT_NODE;)a+=o.textContent,o=o.nextSibling,d++;var s=l(a,r);if(s){for(var f=0;f<d;f++)i.nextSibling.remove();n+=s.childNodes.length-1,t.replaceChild(s,i)}else n+=d}else 1===i.nodeType&&function(){var t=" "+i.className+" ";-1===r.ignoredTags.indexOf(i.nodeName.toLowerCase())&&r.ignoredClasses.every((function(e){return-1===t.indexOf(" "+e+" ")}))&&e(i,r)}()}},s=function(e,t){if(!e)throw new Error("No element provided to render");var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);r.delimiters=r.delimiters||[{left:"$$",right:"$$",display:!0},{left:"\\(",right:"\\)",display:!1},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"\\begin{align}",right:"\\end{align}",display:!0},{left:"\\begin{alignat}",right:"\\end{alignat}",display:!0},{left:"\\begin{gather}",right:"\\end{gather}",display:!0},{left:"\\begin{CD}",right:"\\end{CD}",display:!0},{left:"\\[",right:"\\]",display:!0}],r.ignoredTags=r.ignoredTags||["script","noscript","style","textarea","pre","code","option"],r.ignoredClasses=r.ignoredClasses||[],r.errorCallback=r.errorCallback||console.error,r.macros=r.macros||{},d(e,r)}}(),i=i.default}()}));
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Vendored
-1
File diff suppressed because one or more lines are too long
Vendored
-1
File diff suppressed because one or more lines are too long
@@ -1,12 +0,0 @@
|
||||
const doRender = () => {
|
||||
renderMathInElement(document.body, {
|
||||
delimiters: [
|
||||
{ left: '$$', right: '$$', display: true },
|
||||
{ left: '\\[', right: '\\]', display: true },
|
||||
{ left: '$', right: '$', display: false },
|
||||
{ left: '\\(', right: '\\)', display: false },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
doRender();
|
||||
+15
-11
@@ -1,8 +1,6 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func OptionsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
@@ -10,17 +8,23 @@ func OptionsMiddleware() gin.HandlerFunc {
|
||||
c.Set("theme", "dark")
|
||||
|
||||
imagesCookie, err := c.Cookie("disable_images")
|
||||
if err == nil {
|
||||
if imagesCookie == "true" {
|
||||
c.Set("disable_images", true)
|
||||
}
|
||||
if err != nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if imagesCookie == "true" {
|
||||
c.Set("disable_images", true)
|
||||
}
|
||||
|
||||
themeCookie, err := c.Cookie("theme")
|
||||
if err == nil {
|
||||
if themeCookie == "light" {
|
||||
c.Set("theme", "light")
|
||||
}
|
||||
if err != nil {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
if themeCookie == "light" {
|
||||
c.Set("theme", "light")
|
||||
}
|
||||
|
||||
c.Next()
|
||||
|
||||
+20
-38
@@ -20,41 +20,7 @@ type urlConversionRequest struct {
|
||||
URL string `form:"url" binding:"required"`
|
||||
}
|
||||
|
||||
var coreRegex = regexp.MustCompile(`(?:https?://)?(?:www\.)?([^/]+)(/(?:questions|q|a)/.+)`)
|
||||
|
||||
// Will return `nil` if `rawUrl` is invalid.
|
||||
func translateUrl(rawUrl string) string {
|
||||
coreMatches := coreRegex.FindStringSubmatch(rawUrl)
|
||||
if coreMatches == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
domain := coreMatches[1]
|
||||
rest := coreMatches[2]
|
||||
|
||||
exchange := ""
|
||||
if domain == "stackoverflow.com" {
|
||||
// No exchange parameter needed.
|
||||
} else if sub, found := strings.CutSuffix(domain, ".stackexchange.com"); found {
|
||||
if sub == "" {
|
||||
return ""
|
||||
} else if strings.Contains(sub, ".") {
|
||||
// Anything containing dots is interpreted as a full domain, so we use the correct full domain.
|
||||
exchange = domain
|
||||
} else {
|
||||
exchange = sub
|
||||
}
|
||||
} else {
|
||||
exchange = domain
|
||||
}
|
||||
|
||||
// Ensure we properly format the return string to avoid double slashes
|
||||
if exchange == "" {
|
||||
return rest
|
||||
} else {
|
||||
return fmt.Sprintf("/exchange/%s%s", exchange, rest)
|
||||
}
|
||||
}
|
||||
var stackExchangeRegex = regexp.MustCompile(`https://(.+).stackexchange.com/questions/`)
|
||||
|
||||
func PostHome(c *gin.Context) {
|
||||
body := urlConversionRequest{}
|
||||
@@ -67,9 +33,16 @@ func PostHome(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
translated := translateUrl(body.URL)
|
||||
soLink := body.URL
|
||||
|
||||
if translated == "" {
|
||||
// remove the www.
|
||||
soLink = strings.ReplaceAll(soLink, "www.", "")
|
||||
|
||||
// validate URL
|
||||
isStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/questions/")
|
||||
isShortenedStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/a/")
|
||||
isStackExchange := stackExchangeRegex.MatchString(soLink)
|
||||
if !isStackExchange && !isStackOverflow && !isShortenedStackOverflow {
|
||||
c.HTML(400, "home.html", gin.H{
|
||||
"errorMessage": "Invalid stack overflow/exchange URL",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
@@ -77,5 +50,14 @@ func PostHome(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.Redirect(302, translated)
|
||||
// if stack overflow, trim https://stackoverflow.com
|
||||
if isStackOverflow || isShortenedStackOverflow {
|
||||
c.Redirect(302, strings.TrimPrefix(soLink, "https://stackoverflow.com"))
|
||||
return
|
||||
}
|
||||
|
||||
// if stack exchange, extract the subdomain
|
||||
sub := stackExchangeRegex.FindStringSubmatch(soLink)[1]
|
||||
|
||||
c.Redirect(302, fmt.Sprintf("/exchange/%s/%s", sub, strings.TrimPrefix(soLink, fmt.Sprintf("https://%s.stackexchange.com", sub))))
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestTranslateUrl(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
// Test with a Valid StackOverflow URL
|
||||
assert.Equal("/questions/example-question", translateUrl("https://stackoverflow.com/questions/example-question"), "StackOverflow URL should not be modified")
|
||||
|
||||
// Test with Complex Subdomain
|
||||
assert.Equal("/exchange/meta.math.stackexchange.com/q/example-question", translateUrl("https://meta.math.stackexchange.com/q/example-question"), "Complex StackExchange subdomain should be used as full exchange")
|
||||
|
||||
// Test with Non-StackExchange Domain
|
||||
assert.Equal("/exchange/example.com/questions/example-question", translateUrl("https://example.com/questions/example-question"), "Non-StackExchange domain should be detected as exchange")
|
||||
|
||||
// Test with Invalid URL
|
||||
assert.Equal("", translateUrl("This is not a URL"), "Invalid URL should return an empty string")
|
||||
|
||||
// Test with Empty String
|
||||
assert.Equal("", translateUrl(""), "Empty string should return an empty string")
|
||||
|
||||
// Test with Missing Path
|
||||
assert.Equal("", translateUrl("https://stackoverflow.com"), "URL without path should return an empty string")
|
||||
|
||||
// Test with Valid URL but Root Domain for StackExchange
|
||||
assert.Equal("", translateUrl("https://stackexchange.com"), "Root StackExchange domain without subdomain should return an empty string")
|
||||
}
|
||||
@@ -30,10 +30,12 @@ func ChangeOptions(c *gin.Context) {
|
||||
if c.MustGet("theme").(string) == "dark" {
|
||||
text = "light"
|
||||
}
|
||||
|
||||
c.SetCookie("theme", text, 60*60*24*365*10, "/", "", false, true)
|
||||
// get redirect url from query
|
||||
redirectUrl := c.Query("redirect_url")
|
||||
if redirectUrl == "" {
|
||||
redirectUrl = os.Getenv("APP_URL")
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(redirectUrl, os.Getenv("APP_URL")) {
|
||||
redirectUrl = os.Getenv("APP_URL")
|
||||
|
||||
+195
-177
@@ -29,6 +29,7 @@ var soSortValues = map[string]string{
|
||||
}
|
||||
|
||||
func ViewQuestion(c *gin.Context) {
|
||||
client := resty.New()
|
||||
|
||||
questionId := c.Param("id")
|
||||
if _, err := strconv.Atoi(questionId); err != nil {
|
||||
@@ -40,26 +41,42 @@ func ViewQuestion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
params, err := parseAndValidateParameters(c)
|
||||
if err != nil {
|
||||
return
|
||||
questionTitle := c.Param("title")
|
||||
|
||||
sortValue := c.Query("sort_by")
|
||||
if sortValue == "" {
|
||||
sortValue = "votes"
|
||||
}
|
||||
|
||||
soSortValue, ok := soSortValues[sortValue]
|
||||
if !ok {
|
||||
soSortValue = soSortValues["votes"]
|
||||
}
|
||||
|
||||
sub := c.Param("sub")
|
||||
|
||||
domain := "stackoverflow.com"
|
||||
|
||||
if strings.Contains(params.Sub, ".") {
|
||||
domain = params.Sub
|
||||
} else if params.Sub != "" {
|
||||
domain = fmt.Sprintf("%s.stackexchange.com", params.Sub)
|
||||
if sub != "" {
|
||||
domain = fmt.Sprintf("%s.stackexchange.com", sub)
|
||||
}
|
||||
|
||||
soLink := fmt.Sprintf("https://%s/questions/%s/%s?answertab=%s", domain, questionId, params.QuestionTitle, params.SoSortValue)
|
||||
soLink := fmt.Sprintf("https://%s/questions/%s/%s?answertab=%s", domain, questionId, questionTitle, soSortValue)
|
||||
|
||||
resp, err := fetchQuestionData(soLink)
|
||||
resp, err := client.R().Get(soLink)
|
||||
if err != nil {
|
||||
c.HTML(500, "home.html", gin.H{
|
||||
"errorMessage": "Unable to fetch question data",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"version": config.Version,
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.RawResponse.Body.Close()
|
||||
|
||||
if resp.StatusCode() != 200 {
|
||||
c.HTML(500, "home.html", gin.H{
|
||||
"errorMessage": fmt.Sprintf("Received a non-OK status code %d", resp.StatusCode()),
|
||||
"errorMessage": "Received a non-OK status code",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"version": config.Version,
|
||||
})
|
||||
@@ -80,26 +97,182 @@ func ViewQuestion(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
newFilteredQuestion, err := extractQuestionData(doc, domain)
|
||||
newFilteredQuestion := types.FilteredQuestion{}
|
||||
|
||||
questionTextParent := doc.Find("h1.fs-headline1")
|
||||
|
||||
questionText := questionTextParent.Children().First().Text()
|
||||
|
||||
newFilteredQuestion.Title = questionText
|
||||
|
||||
questionPostLayout := doc.Find("div.post-layout").First()
|
||||
|
||||
questionTags := utils.GetPostTags(questionPostLayout)
|
||||
newFilteredQuestion.Tags = questionTags
|
||||
|
||||
questionBodyParent := doc.Find("div.s-prose")
|
||||
|
||||
questionBodyParentHTML, err := questionBodyParent.Html()
|
||||
if err != nil {
|
||||
c.HTML(500, "home.html", gin.H{
|
||||
"errorMessage": "Failed to extract question data",
|
||||
"errorMessage": "Unable to parse question body",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"version": config.Version,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
answers, err := extractAnswersData(doc, domain)
|
||||
if err != nil {
|
||||
c.HTML(500, "home.html", gin.H{
|
||||
"errorMessage": "Failed to extract answer data",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"version": config.Version,
|
||||
})
|
||||
return
|
||||
newFilteredQuestion.Body = template.HTML(utils.ReplaceImgTags(questionBodyParentHTML))
|
||||
|
||||
questionBodyText := questionBodyParent.Text()
|
||||
|
||||
// remove all whitespace to create the shortened body desc
|
||||
shortenedBody := strings.TrimSpace(questionBodyText)
|
||||
|
||||
// remove all newlines
|
||||
shortenedBody = strings.ReplaceAll(shortenedBody, "\n", " ")
|
||||
|
||||
// get the first 50 chars
|
||||
shortenedBody = shortenedBody[:50]
|
||||
|
||||
newFilteredQuestion.ShortenedBody = shortenedBody
|
||||
|
||||
comments := utils.FindAndReturnComments(questionBodyParentHTML, domain, questionPostLayout)
|
||||
newFilteredQuestion.Comments = comments
|
||||
|
||||
// parse any code blocks and highlight them
|
||||
answerCodeBlocks := questionCodeBlockRegex.FindAllString(questionBodyParentHTML, -1)
|
||||
for _, codeBlock := range answerCodeBlocks {
|
||||
codeBlock = utils.StripBlockTags(codeBlock)
|
||||
|
||||
// syntax highlight
|
||||
highlightedCodeBlock := utils.HighlightSyntaxViaContent(codeBlock)
|
||||
|
||||
// replace the code block with the highlighted code block
|
||||
questionBodyParentHTML = strings.Replace(questionBodyParentHTML, codeBlock, highlightedCodeBlock, 1)
|
||||
}
|
||||
|
||||
questionCard := doc.Find("div.postcell")
|
||||
|
||||
questionMetadata := questionCard.Find("div.user-info")
|
||||
questionTimestamp := ""
|
||||
questionMetadata.Find("span.relativetime").Each(func(i int, s *goquery.Selection) {
|
||||
// get the second
|
||||
if i == 0 {
|
||||
if s.Text() != "" {
|
||||
// if it's not been edited, it means it's the first
|
||||
questionTimestamp = s.Text()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// otherwise it's the second element
|
||||
if i == 1 {
|
||||
questionTimestamp = s.Text()
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
newFilteredQuestion.Timestamp = questionTimestamp
|
||||
|
||||
userDetails := questionMetadata.Find("div.user-details")
|
||||
|
||||
questionAuthor := ""
|
||||
questionAuthorURL := fmt.Sprintf("https://%s", domain)
|
||||
|
||||
// check if the question has been edited
|
||||
isQuestionEdited := false
|
||||
questionMetadata.Find("a.js-gps-track").Each(func(i int, s *goquery.Selection) {
|
||||
if strings.Contains(s.Text(), "edited") {
|
||||
isQuestionEdited = true
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
userDetails.Find("a").Each(func(i int, s *goquery.Selection) {
|
||||
// if question has been edited, the author is the second element.
|
||||
|
||||
if isQuestionEdited {
|
||||
if i == 1 {
|
||||
questionAuthor = s.Text()
|
||||
questionAuthorURL += s.AttrOr("href", "")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// otherwise it's the first element
|
||||
if i == 0 {
|
||||
questionAuthor = s.Text()
|
||||
questionAuthorURL += s.AttrOr("href", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
newFilteredQuestion.AuthorName = questionAuthor
|
||||
newFilteredQuestion.AuthorURL = questionAuthorURL
|
||||
|
||||
answers := []types.FilteredAnswer{}
|
||||
|
||||
doc.Find("div.answer").Each(func(i int, s *goquery.Selection) {
|
||||
|
||||
newFilteredAnswer := types.FilteredAnswer{}
|
||||
|
||||
postLayout := s.Find("div.post-layout")
|
||||
voteCell := postLayout.Find("div.votecell")
|
||||
answerCell := postLayout.Find("div.answercell")
|
||||
answerBody := answerCell.Find("div.s-prose")
|
||||
answerBodyHTML, _ := answerBody.Html()
|
||||
|
||||
voteCount := html.EscapeString(voteCell.Find("div.js-vote-count").Text())
|
||||
|
||||
newFilteredAnswer.Upvotes = voteCount
|
||||
newFilteredAnswer.IsAccepted = s.HasClass("accepted-answer")
|
||||
|
||||
answerFooter := s.Find("div.mt24")
|
||||
|
||||
answerAuthorURL := fmt.Sprintf("https://%s", domain)
|
||||
answerAuthorName := ""
|
||||
answerTimestamp := ""
|
||||
|
||||
answerFooter.Find("div.post-signature").Each(func(i int, s *goquery.Selection) {
|
||||
answerAuthorDetails := s.Find("div.user-details")
|
||||
|
||||
if answerAuthorDetails.Length() > 0 {
|
||||
questionAuthor := answerAuthorDetails.Find("a").First()
|
||||
answerAuthorName = html.EscapeString(questionAuthor.Text())
|
||||
answerAuthorURL += html.EscapeString(questionAuthor.AttrOr("href", ""))
|
||||
}
|
||||
|
||||
answerTimestamp = html.EscapeString(s.Find("span.relativetime").Text())
|
||||
})
|
||||
|
||||
answerId, _ := s.Attr("data-answerid")
|
||||
newFilteredAnswer.ID = answerId
|
||||
|
||||
newFilteredAnswer.AuthorName = answerAuthorName
|
||||
newFilteredAnswer.AuthorURL = answerAuthorURL
|
||||
newFilteredAnswer.Timestamp = answerTimestamp
|
||||
|
||||
// parse any code blocks and highlight them
|
||||
answerCodeBlocks := codeBlockRegex.FindAllString(answerBodyHTML, -1)
|
||||
for _, codeBlock := range answerCodeBlocks {
|
||||
codeBlock = utils.StripBlockTags(codeBlock)
|
||||
|
||||
// syntax highlight
|
||||
highlightedCodeBlock := utils.HighlightSyntaxViaContent(codeBlock)
|
||||
|
||||
// replace the code block with the highlighted code block
|
||||
answerBodyHTML = strings.Replace(answerBodyHTML, codeBlock, highlightedCodeBlock, 1)
|
||||
}
|
||||
|
||||
comments = utils.FindAndReturnComments(answerBodyHTML, domain, postLayout)
|
||||
|
||||
newFilteredAnswer.Comments = comments
|
||||
newFilteredAnswer.Body = template.HTML(utils.ReplaceImgTags(answerBodyHTML))
|
||||
|
||||
answers = append(answers, newFilteredAnswer)
|
||||
})
|
||||
|
||||
imagePolicy := "'self' https:"
|
||||
|
||||
if c.MustGet("disable_images").(bool) {
|
||||
@@ -111,164 +284,9 @@ func ViewQuestion(c *gin.Context) {
|
||||
"answers": answers,
|
||||
"imagePolicy": imagePolicy,
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"currentUrl": fmt.Sprintf("%s%s", os.Getenv("APP_URL"), c.Request.URL.Path),
|
||||
"sortValue": params.SoSortValue,
|
||||
"currentUrl": fmt.Sprintf("%s/questions/%s/%s", os.Getenv("APP_URL"), questionId, questionTitle),
|
||||
"sortValue": sortValue,
|
||||
"domain": domain,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
type viewQuestionInputs struct {
|
||||
QuestionID string
|
||||
QuestionTitle string
|
||||
SoSortValue string
|
||||
Sub string
|
||||
}
|
||||
|
||||
// parseAndValidateParameters consolidates the URL and query parameters into an easily-accessible struct.
|
||||
func parseAndValidateParameters(c *gin.Context) (inputs viewQuestionInputs, err error) {
|
||||
|
||||
questionId := c.Param("id")
|
||||
if _, err = strconv.Atoi(questionId); err != nil {
|
||||
c.HTML(400, "home.html", gin.H{
|
||||
"errorMessage": "Invalid question ID",
|
||||
"theme": c.MustGet("theme").(string),
|
||||
"version": config.Version,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
inputs.QuestionID = questionId
|
||||
|
||||
sortValue := c.Query("sort_by")
|
||||
if sortValue == "" {
|
||||
sortValue = "votes"
|
||||
}
|
||||
|
||||
soSortValue, ok := soSortValues[sortValue]
|
||||
if !ok {
|
||||
soSortValue = soSortValues["votes"]
|
||||
}
|
||||
|
||||
inputs.SoSortValue = soSortValue
|
||||
|
||||
sub := c.Param("sub")
|
||||
|
||||
inputs.Sub = sub
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// fetchQuestionData sends the request to StackOverflow.
|
||||
func fetchQuestionData(soLink string) (resp *resty.Response, err error) {
|
||||
client := resty.New()
|
||||
resp, err = client.R().Get(soLink)
|
||||
return
|
||||
}
|
||||
|
||||
// extractQuestionData parses the HTML document and extracts question data.
|
||||
func extractQuestionData(doc *goquery.Document, domain string) (question types.FilteredQuestion, err error) {
|
||||
// Extract the question title.
|
||||
questionTextParent := doc.Find("h1.fs-headline1").First()
|
||||
question.Title = strings.TrimSpace(questionTextParent.Children().First().Text())
|
||||
|
||||
// Extract question tags.
|
||||
questionTags := utils.GetPostTags(doc.Find("div.post-layout").First())
|
||||
question.Tags = questionTags
|
||||
|
||||
// Extract and process the question body.
|
||||
questionBodyParent := doc.Find("div.s-prose").First()
|
||||
questionBodyParentHTML, err := questionBodyParent.Html()
|
||||
if err != nil {
|
||||
return question, err
|
||||
}
|
||||
question.Body = template.HTML(utils.ProcessHTMLBody(questionBodyParentHTML))
|
||||
|
||||
// Extract the shortened body description.
|
||||
shortenedBody := strings.TrimSpace(questionBodyParent.Text())
|
||||
shortenedBody = strings.ReplaceAll(shortenedBody, "\n", " ")
|
||||
if len(shortenedBody) > 50 {
|
||||
shortenedBody = shortenedBody[:50]
|
||||
}
|
||||
question.ShortenedBody = shortenedBody
|
||||
|
||||
// Extract question comments.
|
||||
comments := utils.FindAndReturnComments(questionBodyParentHTML, domain, doc.Find("div.post-layout").First())
|
||||
question.Comments = comments
|
||||
|
||||
// Extract question timestamp and author information.
|
||||
questionCard := doc.Find("div.postcell").First()
|
||||
extractMetadata(questionCard, &question, domain)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// extractMetadata extracts author and timestamp information from a given selection.
|
||||
func extractMetadata(selection *goquery.Selection, question *types.FilteredQuestion, domain string) {
|
||||
questionMetadata := selection.Find("div.user-info").First()
|
||||
question.Timestamp = questionMetadata.Find("span.relativetime").First().Text()
|
||||
|
||||
questionAuthorURL := "https://" + domain
|
||||
questionAuthor := selection.Find("div.post-signature.owner div.user-info div.user-details a").First()
|
||||
question.AuthorName = questionAuthor.Text()
|
||||
questionAuthorURL += questionAuthor.AttrOr("href", "")
|
||||
question.AuthorURL = questionAuthorURL
|
||||
|
||||
// Determine if the question has been edited and update author details accordingly.
|
||||
isQuestionEdited := selection.Find("a.js-gps-track").Text() == "edited"
|
||||
if isQuestionEdited {
|
||||
editedAuthor := questionMetadata.Find("a").Last()
|
||||
question.AuthorName = editedAuthor.Text()
|
||||
question.AuthorURL = "https://" + domain + editedAuthor.AttrOr("href", "")
|
||||
}
|
||||
}
|
||||
|
||||
// extractAnswersData parses the HTML document and extracts answers data.
|
||||
func extractAnswersData(doc *goquery.Document, domain string) ([]types.FilteredAnswer, error) {
|
||||
var answers []types.FilteredAnswer
|
||||
|
||||
// Iterate over each answer block.
|
||||
doc.Find("div.answer").Each(func(i int, s *goquery.Selection) {
|
||||
var answer types.FilteredAnswer
|
||||
|
||||
postLayout := s.Find("div.post-layout").First()
|
||||
|
||||
// Extract upvotes.
|
||||
voteCell := postLayout.Find("div.votecell").First()
|
||||
voteCount := html.EscapeString(voteCell.Find("div.js-vote-count").Text())
|
||||
answer.Upvotes = voteCount
|
||||
|
||||
// Check if the answer is accepted.
|
||||
answer.IsAccepted = s.HasClass("accepted-answer")
|
||||
|
||||
// Extract answer body and process it.
|
||||
answerCell := postLayout.Find("div.answercell").First()
|
||||
answerBody := answerCell.Find("div.s-prose").First()
|
||||
answerBodyHTML, _ := answerBody.Html()
|
||||
|
||||
// Process code blocks within the answer.
|
||||
processedAnswerBody := utils.ProcessHTMLBody(answerBodyHTML)
|
||||
answer.Body = template.HTML(processedAnswerBody)
|
||||
|
||||
// Extract author information and timestamp.
|
||||
extractAnswerAuthorInfo(s, &answer, domain)
|
||||
|
||||
answers = append(answers, answer)
|
||||
})
|
||||
|
||||
return answers, nil
|
||||
}
|
||||
|
||||
// extractAnswerAuthorInfo extracts the author name, URL, and timestamp from an answer block.
|
||||
// It directly mutates the answer.
|
||||
func extractAnswerAuthorInfo(selection *goquery.Selection, answer *types.FilteredAnswer, domain string) {
|
||||
authorDetails := selection.Find("div.post-signature").Last()
|
||||
|
||||
authorName := html.EscapeString(authorDetails.Find("div.user-details a").First().Text())
|
||||
authorURL := "https://" + domain + authorDetails.Find("div.user-details a").AttrOr("href", "")
|
||||
timestamp := html.EscapeString(authorDetails.Find("span.relativetime").Text())
|
||||
|
||||
answer.AuthorName = authorName
|
||||
answer.AuthorURL = authorURL
|
||||
answer.Timestamp = timestamp
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
|
||||
func RedirectShortenedOverflowURL(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
answerId := c.Param("answerId")
|
||||
|
||||
// fetch the stack overflow URL
|
||||
client := resty.New()
|
||||
@@ -21,7 +20,7 @@ func RedirectShortenedOverflowURL(c *gin.Context) {
|
||||
}),
|
||||
)
|
||||
|
||||
resp, err := client.R().Get(fmt.Sprintf("https://www.stackoverflow.com/a/%s/%s", id, answerId))
|
||||
resp, err := client.R().Get(fmt.Sprintf("https://www.stackoverflow.com/a/%s", id))
|
||||
if err != nil {
|
||||
c.HTML(400, "home.html", gin.H{
|
||||
"errorMessage": "Unable to fetch stack overflow URL",
|
||||
|
||||
@@ -50,7 +50,7 @@ func FindAndReturnComments(inHtml, domain string, postLayout *goquery.Selection)
|
||||
commentTimestamp := commentBody.Find("span.relativetime-clean").Text()
|
||||
|
||||
newFilteredComment := types.FilteredComment{
|
||||
Text: template.HTML(ProcessHTMLBody(commentCopy)),
|
||||
Text: template.HTML(commentCopy),
|
||||
Timestamp: commentTimestamp,
|
||||
AuthorName: commentAuthor.Text(),
|
||||
AuthorURL: commentAuthorURL,
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// stackOverflowLinkQualifierRegex matches all anchor elements that meet the following conditions:
|
||||
// * must be an anchor element
|
||||
// * the anchor element must have a pathname beginning with /q or /questions
|
||||
// * if there is a host, it must be stackoverflow.com or a subdomain
|
||||
var stackOverflowLinkQualifierRegex = regexp.MustCompile(`<a\s[^>]*href="(?:https?://(?:www\.)?(?:\w+\.)*(?:stackoverflow|stackexchange)\.com)?/(?:q|questions)/[^"]*"[^>]*>.*?</a>`)
|
||||
|
||||
func ReplaceStackOverflowLinks(html string) string {
|
||||
return stackOverflowLinkQualifierRegex.ReplaceAllStringFunc(html, func(match string) string {
|
||||
// Extract the href attribute value from the anchor tag
|
||||
hrefRegex := regexp.MustCompile(`href="([^"]*)"`)
|
||||
hrefMatch := hrefRegex.FindStringSubmatch(match)
|
||||
if len(hrefMatch) < 2 {
|
||||
return match
|
||||
}
|
||||
href := hrefMatch[1]
|
||||
|
||||
// Parse the URL
|
||||
url, err := url.Parse(href)
|
||||
if err != nil {
|
||||
return match
|
||||
}
|
||||
|
||||
newUrl := url.String()
|
||||
|
||||
// Check if the host is a subdomain
|
||||
parts := strings.Split(url.Host, ".")
|
||||
if len(parts) > 2 {
|
||||
// Prepend the subdomain to the path
|
||||
url.Path = "/exchange/" + parts[0] + url.Path
|
||||
}
|
||||
|
||||
newUrl = url.Path + url.RawQuery + url.Fragment
|
||||
|
||||
// Replace the href attribute value in the anchor tag
|
||||
return strings.Replace(match, hrefMatch[1], newUrl, 1)
|
||||
})
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var sampleInput = `<div class="d-flex fd-column fw-nowrap">
|
||||
<div class="d-flex fw-nowrap">
|
||||
<div class="flex--item wmn0 fl1 lh-lg">
|
||||
<div class="flex--item fl1 lh-lg">
|
||||
<div>
|
||||
<b>This question already has answers here</b>:
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex--item mb0 mt4">
|
||||
<a href="/questions/55083952/is-it-possible-to-populate-a-large-set-at-compile-time" dir="ltr">Is it possible to populate a large set at compile time?</a>
|
||||
<span class="question-originals-answer-count">
|
||||
(3 answers)
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex--item mb0 mt4">
|
||||
<a href="https://stackoverflow.com/questions/27221504/how-can-you-make-a-safe-static-singleton-in-rust" dir="ltr">How can you make a safe static singleton in Rust?</a>
|
||||
<span class="question-originals-answer-count">
|
||||
(5 answers)
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex--item mb0 mt4">
|
||||
<a href="https://security.stackexchange.com/questions/25371/brute-force-an-ssh-login-that-has-only-a-4-letter-password" dir="ltr">Brute-force an SSH-login that has only a 4-letter password</a>
|
||||
<span class="question-originals-answer-count">
|
||||
(9 answers)
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex--item mb0 mt8">Closed <span title="2020-01-29 14:28:42Z" class="relativetime">4 years ago</span>.</div>
|
||||
</div>`
|
||||
|
||||
func TestReplaceStackOverflowLinks(t *testing.T) {
|
||||
replacedLinks := ReplaceStackOverflowLinks(sampleInput)
|
||||
|
||||
fmt.Println(replacedLinks)
|
||||
|
||||
assert.False(t, strings.Contains(replacedLinks, "stackoverflow.com"))
|
||||
assert.False(t, strings.Contains(replacedLinks, "stackexchange.com"))
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package utils
|
||||
|
||||
// ProcessHTMLBody runs HTML through the various preparation functions.
|
||||
func ProcessHTMLBody(bodyHTML string) string {
|
||||
highlightedBody := HighlightCodeBlocks(bodyHTML)
|
||||
imageProxiedBody := ReplaceImgTags(highlightedBody)
|
||||
stackOverflowLinksReplacedBody := ReplaceStackOverflowLinks(imageProxiedBody)
|
||||
return stackOverflowLinksReplacedBody
|
||||
}
|
||||
+7
-35
@@ -12,19 +12,17 @@ import (
|
||||
"github.com/alecthomas/chroma/styles"
|
||||
)
|
||||
|
||||
// highlightSyntaxViaContent uses Chroma to lex code content and apply the appropriate tokenizer engine.
|
||||
// If it can't find one, it defaults to JavaScript syntax highlighting.
|
||||
func highlightSyntaxViaContent(content string, lang string) (htmlOut string) {
|
||||
func HighlightSyntaxViaContent(content string) (htmlOut string) {
|
||||
content = html.UnescapeString(content)
|
||||
|
||||
fallbackOut := html.EscapeString(content)
|
||||
|
||||
lexer := lexers.Get(lang)
|
||||
// identify the language
|
||||
lexer := lexers.Analyse(content)
|
||||
if lexer == nil {
|
||||
lexer = lexers.Analyse(content)
|
||||
}
|
||||
if lexer == nil {
|
||||
lexer = lexers.Get(".js")
|
||||
// unable to identify, so just return the wrapped content
|
||||
htmlOut = fallbackOut
|
||||
return
|
||||
}
|
||||
|
||||
style := styles.Get("xcode")
|
||||
@@ -56,9 +54,7 @@ func highlightSyntaxViaContent(content string, lang string) (htmlOut string) {
|
||||
|
||||
var preClassRegex = regexp.MustCompile(`(?s)<pre class=".+">`)
|
||||
|
||||
// stripBlockTags takes an extracted code block from HTML and strips it of its pre and code tags.
|
||||
// What's returned is just the code.
|
||||
func stripBlockTags(content string) (result string) {
|
||||
func StripBlockTags(content string) (result string) {
|
||||
// strip all "<code>" tags
|
||||
content = strings.Replace(content, "<code>", "", -1)
|
||||
content = strings.Replace(content, "</code>", "", -1)
|
||||
@@ -72,27 +68,3 @@ func stripBlockTags(content string) (result string) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var codeBlockRegex = regexp.MustCompile(`(?s)<pre(?:[^>]+?lang-(.+?)[\s"'])?.*?><code>(.*?)<\/code><\/pre>`)
|
||||
|
||||
// HighlightCodeBlocks uses both highlightSyntaxViaContent stripCodeBlocks and returns the newly highlighted code HTML.
|
||||
func HighlightCodeBlocks(html string) string {
|
||||
// Replace each code block with the highlighted version
|
||||
highlightedHTML := codeBlockRegex.ReplaceAllStringFunc(html, func(codeBlock string) string {
|
||||
// Extract the code content from the code block
|
||||
matches := codeBlockRegex.FindStringSubmatch(codeBlock)
|
||||
lang, codeContent := matches[1], matches[2]
|
||||
|
||||
codeContent = stripBlockTags(codeContent)
|
||||
|
||||
// Highlight the code content
|
||||
highlightedCode := highlightSyntaxViaContent(codeContent, lang)
|
||||
|
||||
// Replace the original code block with the highlighted version
|
||||
highlightedCodeBlock := "<pre>" + highlightedCode + "</pre>"
|
||||
|
||||
return highlightedCodeBlock
|
||||
})
|
||||
|
||||
return highlightedHTML
|
||||
}
|
||||
|
||||
+2
-10
@@ -7,19 +7,11 @@
|
||||
<link rel="stylesheet" href="/static/comments.css" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'none'; style-src 'self'; script-src 'self'; img-src {{ .imagePolicy }}; font-src 'self';"
|
||||
content="default-src 'none'; style-src 'self'; script-src 'none'; img-src {{ .imagePolicy }};"
|
||||
/>
|
||||
<meta name="description" content="{{ .question.ShortenedBody }}..." />
|
||||
{{ template "sharedHead.html" }}
|
||||
<link rel="stylesheet" href="/static/katex/katex.min.css">
|
||||
|
||||
<!-- The loading of KaTeX is deferred to speed up page rendering -->
|
||||
<script defer src="/static/katex/katex.min.js"></script>
|
||||
|
||||
<!-- To automatically render math in text elements, include the auto-render extension: -->
|
||||
<script defer src="/static/katex/contrib/auto-render.min.js"></script>
|
||||
<script defer src="/static/question.js" type="text/javascript"></script>
|
||||
</head>
|
||||
</head>
|
||||
<body>
|
||||
<div class="parent">
|
||||
<div class="header">
|
||||
|
||||
Reference in New Issue
Block a user