add backend supporting opengraph and comments

This commit is contained in:
2024-11-29 19:14:12 -07:00
parent 09a0c44e50
commit d2efb2f0cb
15 changed files with 633 additions and 167 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/local.sqlite

1
.idea/.name generated Normal file
View File

@ -0,0 +1 @@
any-remark

15
.idea/dataSources.xml generated Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="local.sqlite" uuid="9d24f14e-4852-4304-adb5-d3026280fd67">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:local.sqlite</jdbc-url>
<jdbc-additional-properties>
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
</jdbc-additional-properties>
<working-dir>$ProjectFileDir$</working-dir>
</data-source>
</component>
</project>

2
.idea/modules.xml generated
View File

@ -2,7 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/comment-anywhere.iml" filepath="$PROJECT_DIR$/.idea/comment-anywhere.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/any-remark.iml" filepath="$PROJECT_DIR$/.idea/any-remark.iml" />
</modules>
</component>
</project>

151
backend/datastore/mapper.go Normal file
View File

@ -0,0 +1,151 @@
package datastore
import (
"database/sql"
"fmt"
"git.sa.vin/any-remark/backend/types"
"math/rand"
)
type Mapper interface {
GetOpenGraphData(url string) (string, error)
SaveOpenGraphData(url, opengraph string) error
AddComment(req types.AddCommentRequest) error
GetComments(url string) ([]types.Comment, error)
}
type mapper struct {
db *sql.DB
}
func NewMapper(db *sql.DB) Mapper {
// Empty function for NewMapper
return &mapper{
db: db,
}
}
func (m *mapper) GetOpenGraphData(url string) (string, error) {
// get the opengraph data from the db table named "webpages" using the url
query := `SELECT opengraph FROM webpages WHERE url = ?`
rows, err := m.db.Query(query, url)
if err != nil {
if err == sql.ErrNoRows {
return "", fmt.Errorf("no data found in db for url: %s", url)
}
return "", fmt.Errorf("error getting webpage data from db: %s", err)
}
defer rows.Close()
// get the opengraph data from the rows array
var opengraph string
for rows.Next() {
err = rows.Scan(&opengraph)
if err != nil {
return "", fmt.Errorf("error scanning opengraph data: %s", err)
}
return opengraph, nil
}
return "", fmt.Errorf("no data found in db for url: %s", url)
}
// SaveOpenGraphData saves the opengraph data to the db
func (m *mapper) SaveOpenGraphData(url, opengraph string) error {
// generate a unique id for the webpage make it 24 bytes long
id := "wp_" + generateID(24)
// insert the opengraph data to the db table named "webpages" using the url
query := `INSERT INTO webpages (id, url, opengraph) VALUES (?, ?, ?)`
_, err := m.db.Exec(query, id, url, opengraph)
if err != nil {
return fmt.Errorf("error inserting webpage data to db: %s", err)
}
return nil
}
func (m *mapper) GetWebpageID(url string) (string, error) {
// get the id of the webpage from the db table named "webpages" using the url
query := `SELECT id FROM webpages WHERE url = ?`
rows, err := m.db.Query(query, url)
if err != nil {
if err == sql.ErrNoRows {
return "", fmt.Errorf("no data found in db for url: %s", url)
}
return "", fmt.Errorf("error getting webpage data from db: %s", err)
}
defer rows.Close()
// get the id from the rows array
var id string
for rows.Next() {
err = rows.Scan(&id)
if err != nil {
return "", fmt.Errorf("error scanning webpage id: %s", err)
}
return id, nil
}
return "", fmt.Errorf("no data found in db for url: %s", url)
}
func (m *mapper) AddComment(req types.AddCommentRequest) error {
webpageID, err := m.GetWebpageID(req.URL)
if err != nil {
return fmt.Errorf("error getting webpage id: %s", err)
}
// generate a unique id for the comment make it 24 bytes long
id := "c_" + generateID(24)
// insert the comment data to the db table named "comments" using the url
query := `INSERT INTO comments (id, content, webpage_id, commenter) VALUES (?, ?, ?, ?)`
_, err = m.db.Exec(query, id, req.Comment, webpageID, req.UserID)
if err != nil {
return fmt.Errorf("error inserting comment data to db: %s", err)
}
return nil
}
func (m *mapper) GetComments(url string) ([]types.Comment, error) {
webpageID, err := m.GetWebpageID(url)
if err != nil {
return nil, fmt.Errorf("error getting webpage id: %s", err)
}
// TODO: add up vote and down vote counts
// TODO: attach avatar url to commenter
// TODO: provide order by recent or most upvoted
// TODO: bubble up the current user's comments
// get the comments from the db table named "comments" using the webpage_id
query := `SELECT id, content, commenter FROM comments WHERE webpage_id = ?`
rows, err := m.db.Query(query, webpageID)
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("no data found in db for url: %s", url)
}
return nil, fmt.Errorf("error getting comments from db: %s", err)
}
defer rows.Close()
// get the comments from the rows array
var comments []types.Comment
for rows.Next() {
var comment types.Comment
err = rows.Scan(&comment.ID, &comment.Content, &comment.Commenter)
if err != nil {
return nil, fmt.Errorf("error scanning comments: %s", err)
}
comments = append(comments, comment)
}
return comments, nil
}
func generateID(n int) string {
// generate a unique id for the webpage make it 24 bytes
// long using the following character set
charSet := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
charSetLen := len(charSet)
id := make([]byte, n)
for i := range id {
// choose a random character from the character set
id[i] = charSet[rand.Intn(charSetLen)]
}
return string(id)
}

77
backend/main.go Normal file
View File

@ -0,0 +1,77 @@
package main
import (
"embed"
"git.sa.vin/any-remark/backend/datastore"
"git.sa.vin/any-remark/backend/server"
"github.com/gorilla/mux"
"github.com/payne8/go-libsql-dual-driver"
"github.com/rs/cors"
"log"
"net/http"
"os"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
func main() {
// create an http server for the following routes
// /api/v1/opengraph
// /x/:id -- short links
// /api/v1/shorten -- short link creation
logger := log.New(os.Stdout, "any-remark", log.LstdFlags)
primaryUrl := os.Getenv("LIBSQL_DATABASE_URL")
authToken := os.Getenv("LIBSQL_AUTH_TOKEN")
tdb, err := libsqldb.NewLibSqlDB(
primaryUrl,
libsqldb.WithMigrationFiles(migrationFiles),
libsqldb.WithAuthToken(authToken),
libsqldb.WithLocalDBName("local.db"), // will not be used for remote-only
)
if err != nil {
logger.Printf("failed to open db %s: %s", primaryUrl, err)
log.Fatalln(err)
return
}
err = tdb.Migrate()
if err != nil {
logger.Printf("failed to migrate db %s: %s", primaryUrl, err)
log.Fatalln(err)
return
}
mapper := datastore.NewMapper(tdb.DB)
s := server.NewServer(mapper)
r := mux.NewRouter()
// add allow cors middleware
//r.Use(server.CorsMiddleware)
r.HandleFunc("/api/v1/opengraph", s.OpenGraphHandler).Methods("GET")
r.HandleFunc("/api/v1/shorten", s.ShortenLinkHandler).Methods("POST")
r.HandleFunc("/api/v1/comments", s.ListComments).Methods("GET")
r.HandleFunc("/api/v1/comment", s.AddComment).Methods("POST")
r.HandleFunc("/x/{id}", s.ShortLinkHandler).Methods("GET")
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://localhost:5173"},
AllowCredentials: true,
})
handler := c.Handler(r)
//log.Fatal(http.ListenAndServe(":3000", handler)
http.Handle("/", handler)
err = http.ListenAndServe(":8080", nil)
if err != nil {
logger.Printf("server failed: %s", err)
log.Fatalln(err)
return
}
}

View File

@ -0,0 +1,37 @@
-- all ids will be TEXT
-- make a table for storing webpages and related opengraph information in json format
CREATE TABLE webpages (
id TEXT PRIMARY KEY,
url TEXT NOT NULL UNIQUE,
opengraph JSONB NOT NULL
);
-- add an index to the url column
CREATE INDEX url_index ON webpages (url);
-- make a table for storing comments on webpages and replies to comments
CREATE TABLE comments (
id TEXT PRIMARY KEY,
webpage_id TEXT NOT NULL,
parent_id TEXT, -- NULL if top-level comment
commenter TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- make a table for storing votes on comments and webpages
CREATE TABLE votes (
id TEXT PRIMARY KEY,
webpage_id TEXT NOT NULL,
comment_id TEXT, -- NULL if vote is on webpage
voter TEXT NOT NULL,
vote_type TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- make a table for storing users
CREATE TABLE users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
avatar TEXT NOT NULL
);

150
backend/server/server.go Normal file
View File

@ -0,0 +1,150 @@
package server
import (
"encoding/json"
"fmt"
"git.sa.vin/any-remark/backend/datastore"
"git.sa.vin/any-remark/backend/types"
"github.com/dyatlov/go-opengraph/opengraph"
"net/http"
)
type Server interface {
OpenGraphHandler(w http.ResponseWriter, r *http.Request)
ShortLinkHandler(w http.ResponseWriter, r *http.Request)
ShortenLinkHandler(w http.ResponseWriter, r *http.Request)
AddComment(w http.ResponseWriter, r *http.Request)
ListComments(w http.ResponseWriter, r *http.Request)
}
type server struct {
mapper datastore.Mapper
}
func NewServer(mapper datastore.Mapper) Server {
// Empty function for NewServer
return &server{
mapper: mapper,
}
}
func (s *server) OpenGraphHandler(w http.ResponseWriter, r *http.Request) {
// get the url from the query string
queryParams := r.URL.Query()
url := queryParams.Get("url")
og := opengraph.NewOpenGraph()
if url == "" {
http.Error(w, "url parameter is required", http.StatusBadRequest)
return
}
// check if our db has the url already
// get the opengraph data from the db
ogString, err := s.mapper.GetOpenGraphData(url)
if err != nil || ogString == "" {
// if it doesn't, fetch the opengraph data from the url
// TODO: fetch the url require that it responds with html
resp, err := http.Get(url) // TODO: use an external proxy to fetch the url
if err != nil {
http.Error(w, fmt.Sprintf("error fetching url: %s", err), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
err = og.ProcessHTML(resp.Body)
if err != nil {
// TODO: decide what to do if the given site does not respond with html or doesn't exist etc.
http.Error(w, fmt.Sprintf("error processing html: %s", err), http.StatusInternalServerError)
return
}
// save the opengraph data to the db
err = s.mapper.SaveOpenGraphData(url, og.String())
if err != nil {
http.Error(w, fmt.Sprintf("error saving opengraph data: %s", err), http.StatusInternalServerError)
return
}
// return the opengraph data
w.Header().Set("Content-Type", "application/json")
_, err = w.Write([]byte(og.String()))
if err != nil {
http.Error(w, fmt.Sprintf("error writing opengraph data: %s", err), http.StatusInternalServerError)
return
}
return
}
// return the opengraph data
w.Header().Set("Content-Type", "application/json")
_, err = w.Write([]byte(ogString))
if err != nil {
http.Error(w, fmt.Sprintf("error writing opengraph data: %s", err), http.StatusInternalServerError)
return
}
}
func (s *server) ShortLinkHandler(w http.ResponseWriter, r *http.Request) {
// Empty handler for /x/{id}
}
func (s *server) ShortenLinkHandler(w http.ResponseWriter, r *http.Request) {
// Empty handler for /api/v1/shorten
}
func (s *server) AddComment(w http.ResponseWriter, r *http.Request) {
var req types.AddCommentRequest
// unmarshal the request body into the req struct
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, fmt.Sprintf("error decoding request body: %s", err), http.StatusBadRequest)
return
}
err = s.mapper.AddComment(req)
if err != nil {
http.Error(w, fmt.Sprintf("error adding comment: %s", err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func (s *server) ListComments(w http.ResponseWriter, r *http.Request) {
comments, err := s.mapper.GetComments(r.URL.Query().Get("url"))
if err != nil {
http.Error(w, fmt.Sprintf("error getting comments: %s", err), http.StatusInternalServerError)
return
}
// TODO: add pagination
// return the comments
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(comments)
if err != nil {
http.Error(w, fmt.Sprintf("error encoding comments: %s", err), http.StatusInternalServerError)
return
}
}
// CorsMiddleware is a middleware that allows CORS
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// allow all origins
w.Header().Set("Access-Control-Allow-Origin", "*")
// allow all headers
w.Header().Set("Access-Control-Allow-Headers", "*")
// allow all methods
w.Header().Set("Access-Control-Allow-Methods", "*")
// allow credentials
w.Header().Set("Access-Control-Allow-Credentials", "true")
// handle pre-flight requests
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
// call the next handler
next.ServeHTTP(w, r)
})
}

16
backend/types/types.go Normal file
View File

@ -0,0 +1,16 @@
package types
type AddCommentRequest struct {
Comment string `json:"comment"`
URL string `json:"url"`
UserID string `json:"user_id"`
}
type Comment struct {
ID string `json:"id"`
Content string `json:"content"`
Commenter string `json:"commenter"`
ParentID string `json:"parent_id"`
WebpageID string `json:"webpage_id"`
CreatedAt string `json:"created_at"`
}

24
go.mod Normal file
View File

@ -0,0 +1,24 @@
module git.sa.vin/any-remark
go 1.23.0
require (
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a
github.com/gorilla/handlers v1.5.2
github.com/gorilla/mux v1.8.1
github.com/payne8/go-libsql-dual-driver v0.2.3
github.com/rs/cors v1.11.1
)
require (
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c // indirect
github.com/tursodatabase/go-libsql v0.0.0-20241113154718-293fe7f21b08 // indirect
github.com/tursodatabase/libsql-client-go v0.0.0-20240902231107-85af5b9d094d // indirect
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirect
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 // indirect
)

44
go.sum Normal file
View File

@ -0,0 +1,44 @@
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo=
github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a h1:etIrTD8BQqzColk9nKRusM9um5+1q0iOEJLqfBMIK64=
github.com/dyatlov/go-opengraph/opengraph v0.0.0-20220524092352-606d7b1e5f8a/go.mod h1:emQhSYTXqB0xxjLITTw4EaWZ+8IIQYw+kx9GqNUKdLg=
github.com/felixge/httpsnoop v1.0.3 h1:s/nj+GCswXYzN5v2DpNMuMQYe+0DDwt5WVCU6CWBdXk=
github.com/felixge/httpsnoop v1.0.3/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyEE=
github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c h1:WsJ6G+hkDXIMfQE8FIxnnziT26WmsRgZhdWQ0IQGlcc=
github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c/go.mod h1:gIcFddvsvPcRCO6QDmWH9/zcFd5U26QWWRMgZh4ddyo=
github.com/payne8/go-libsql-dual-driver v0.2.3 h1:ea19rrdn3QQqvDrHNZ5gqqj2Nn7DbhGDVvDL4UDYZ68=
github.com/payne8/go-libsql-dual-driver v0.2.3/go.mod h1:fhe8WdGtBLvGZ5drN9We0uWEedXeCCTvWaTLExrGW9M=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/tursodatabase/go-libsql v0.0.0-20241113154718-293fe7f21b08 h1:dRoVQWkotI/nCTY2yonI727CV+8hOMr7QGsztnTdEaI=
github.com/tursodatabase/go-libsql v0.0.0-20241113154718-293fe7f21b08/go.mod h1:TjsB2miB8RW2Sse8sdxzVTdeGlx74GloD5zJYUC38d8=
github.com/tursodatabase/libsql-client-go v0.0.0-20240902231107-85af5b9d094d h1:dOMI4+zEbDI37KGb0TI44GUAwxHF9cMsIoDTJ7UmgfU=
github.com/tursodatabase/libsql-client-go v0.0.0-20240902231107-85af5b9d094d/go.mod h1:l8xTsYB90uaVdMHXMCxKKLSgw5wLYBwBKKefNIUnm9s=
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f h1:XdNn9LlyWAhLVp6P/i8QYBW+hlyhrhei9uErw2B5GJo=
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f/go.mod h1:D5SMRVC3C2/4+F/DB1wZsLRnSNimn2Sp/NPsCrsv8ak=
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2 h1:NWy5+hlRbC7HK+PmcXVUmW1IMyFce7to56IUvhUFm7Y=
golang.org/x/net v0.0.0-20220520000938-2e3eb7b945c2/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=

View File

@ -1,13 +1,23 @@
<script setup lang="ts">
const props = defineProps({
content: {
type: String,
required: true,
},
avatar: {
type: String,
required: true,
},
});
</script>
<template>
<div class="comment">
<img src="https://cdn.vuetifyjs.com/images/lists/1.jpg" alt="User Avatar" class="avatar"/>
<img :src="props.avatar" alt="User Avatar" class="avatar"/>
<!-- <img src="https://cdn.vuetifyjs.com/images/lists/1.jpg" alt="User Avatar" class="avatar"/>-->
<div class="comment-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.</p>
<p>{{props.content}}</p>
</div>
</div>
</template>

View File

@ -1,5 +1,6 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { onMounted, watch, ref } from 'vue'
const BACKEND_URL = 'http://localhost:8080';
type OpenGraph = {
type: string;
@ -39,7 +40,7 @@ type OpenGraph = {
} | null;
};
const url = defineProps({
const props = defineProps({
url: {
type: String,
required: true,
@ -68,119 +69,24 @@ const og = ref<OpenGraph>({
},
});
function getOpenGraph() {
if (!props.url) {
return;
}
fetch(` ${BACKEND_URL}/api/v1/opengraph?url=${props.url}`)
// fetch(`https://anyremark.com/api/v1/opengraph?url=${url}`)
.then(response => response.json())
.then(data => {
og.value = data;
});
}
watch(() => props.url, () => {
getOpenGraph();
});
onMounted(() => {
// fetch(`https://anyremark.com/api/opengraph?url=${url}`)
// .then(response => response.json())
// .then(data => {
// og.value = data;
// });
// og.value = {
// type: "video.other",
// url: "https://www.youtube.com/watch?v=iedMwhLrFQQ",
// title: "Stingrays with Friends - FPV Formation",
// description: "My favorite thing to do in this hobby is fly FPV with friends and chase planes.Morning FPV flights with Ben and Eric.If you are interested in this plane (The...",
// determiner: "",
// site_name: "YouTube",
// locale: "",
// locales_alternate: "",
// images: [
// {
// url: "https://i.ytimg.com/vi/iedMwhLrFQQ/maxresdefault.jpg",
// secure_url: "",
// type: "",
// width: 1280,
// height: 720
// }
// ],
// audios: [],
// videos: [
// {
// url: "https://www.youtube.com/embed/iedMwhLrFQQ",
// secure_url: "https://www.youtube.com/embed/iedMwhLrFQQ",
// type: "text/html",
// width: 1280,
// height: 720
// }
// ],
// article: {
// published_time: null,
// modified_time: null,
// expiration_time: null,
// section: "",
// tags: null,
// authors: null
// },
// };
console.log(url);
// og.value = {
// "type": "video.other",
// "url": "https://vimeo.com/867950660",
// "title": "Hands Of Sicily.",
// "description": "The hands of a human can tell a million stories. This film is an intimate portrait of Sicily. It simply shows the hands of the people from the island in action.\u0026hellip;",
// "determiner": "",
// "site_name": "Vimeo",
// "locale": "",
// "locales_alternate": null,
// "images": [
// {
// "url": "https://i.vimeocdn.com/video/1728918730-bfdfd12d26406a06d263d62fef2da83aea8a684a0eeff059bb2ae6c41eda4aec-d?f=webp",
// "secure_url": "https://i.vimeocdn.com/video/1728918730-bfdfd12d26406a06d263d62fef2da83aea8a684a0eeff059bb2ae6c41eda4aec-d?f=webp",
// "type": "image/webp",
// "width": 1280,
// "height": 953
// }
// ],
// "audios": null,
// "videos": [
// {
// "url": "https://player.vimeo.com/video/867950660?autoplay=1\u0026amp;h=f094db59eb",
// "secure_url": "https://player.vimeo.com/video/867950660?autoplay=1\u0026amp;h=f094db59eb",
// "type": "text/html",
// "width": 1280,
// "height": 953
// }
// ],
// "article": {
// "published_time": null,
// "modified_time": null,
// "expiration_time": null,
// "section": "",
// "tags": null,
// "authors": null
// }
// };
og.value = {
"type": "article",
"url": "https://github.blog/changelog/2024-11-27-access-a-repositorys-secret-scanning-scan-history-with-the-rest-api/",
"title": "Access a repositorys secret scanning scan history with the REST API · GitHub Changelog",
"description": "Access a repository's secret scanning scan history with the REST API",
"determiner": "",
"site_name": "The GitHub Blog",
"locale": "en_US",
"locales_alternate": null,
"images": [
{
"url": "https://github.blog/wp-content/uploads/2024/08/d34e9c19123898a8a886147f37a1d167130d1c15be6d399a9c4b30ee6f2a7395-1200x630-1.png?fit=1200%2C630",
"secure_url": "",
"type": "image/png",
"width": 1200,
"height": 630
}
],
"audios": null,
"videos": null,
"article": {
"published_time": null,
"modified_time": null,
"expiration_time": null,
"section": "",
"tags": null,
"authors": null
}
};
getOpenGraph();
});
const videoVisible = ref(false);
@ -191,45 +97,14 @@ function showVideo() {
</script>
<template>
<!-- Show the topic webpage's open graph content-->
<!-- server side will use https://github.com/dyatlov/go-opengraph -->
<!-- example opengraph output here
{
"type": "video.other",
"url": "https://www.youtube.com/watch?v=iedMwhLrFQQ",
"title": "Stingrays with Friends - FPV Formation",
"description": "My favorite thing to do in this hobby is fly FPV with friends and chase planes.Morning FPV flights with Ben and Eric.If you are interested in this plane (The...",
"determiner": "",
"site_name": "YouTube",
"locale": "",
"locales_alternate": null,
"images": [
{
"url": "https://i.ytimg.com/vi/iedMwhLrFQQ/maxresdefault.jpg",
"secure_url": "",
"type": "",
"width": 1280,
"height": 720
}
],
"audios": null,
"videos": [
{
"url": "https://www.youtube.com/embed/iedMwhLrFQQ",
"secure_url": "https://www.youtube.com/embed/iedMwhLrFQQ",
"type": "text/html",
"width": 1280,
"height": 720
}
]
}
-->
<article>
<h1><a :href="og.url">{{og.title}}</a></h1>
<p>{{og.description}}</p>
<h1><a :href="!!og.url ? og.url : props.url">{{!!og.title ? og.title : props.url}}</a></h1>
<p v-if="!!og.description">{{og.description}}</p>
<div class="article-thumb-container" v-if="og.type === 'article'">
<img :src="!!og.images.length ? og.images[0].url : ''" alt="Article Thumbnail" />
<a :href="props.url" target="_blank">{{props.url}}</a>
<div class="images-container" v-if="!!og.images?.length && og.type !== 'video.other'">
<img v-on:error="() => og.images = []" :src="!!og.images.length ? og.images[0].url : ''" alt="Article Thumbnail" />
</div>
<div class="video-other" v-if="og.type === 'video.other'">
@ -239,7 +114,7 @@ function showVideo() {
<div class="non-yt-container" v-if="!!og.videos?.length && (!og.url.startsWith('https://www.youtube.com') && !og.url.startsWith('https://vimeo.com'))">
<div class="thumbnail-container" @click="showVideo" v-if="!videoVisible">
<img :src="!!og.images.length ? og.images[0].url : ''" alt="Video Thumbnail" />
<img v-on:error="() => og.images = []" :src="!!og.images.length ? og.images[0].url : ''" alt="Video Thumbnail" />
<div class="play-button"></div>
</div>
<div class="thumbnail-container" v-else>
@ -261,13 +136,13 @@ article {
align-items: flex-start;
}
.article-thumb-container {
.images-container {
width: 100%;
margin-top: 20px;
margin-bottom: 20px;
}
.article-thumb-container img {
.images-container img {
width: 100%;
height: auto;
max-width: 100%;
@ -298,9 +173,6 @@ article {
.non-yt-container, .non-yt-container>div {
width: 100%;
/* padding-bottom: 56.25%;
margin-top: 20px;
margin-bottom: 20px; */
}
.thumbnail-container {

View File

@ -2,10 +2,74 @@
import CommentComponent from '@/components/CommentComponent.vue'
import OpenGraphComponent from '@/components/OpenGraphComponent.vue'
import { ref } from 'vue'
import { onMounted, ref, watch } from 'vue'
const BACKEND_URL = 'http://localhost:8080';
interface Comment {
id: string;
content: string;
commenter: string;
parent_id: string;
webpage_id: string;
created_at: string;
}
// const url = ref('https://www.youtube.com/watch?v=iedMwhLrFQQ');
const url = ref('https://vimeo.com/867950660');
// const url = ref('https://vimeo.com/867950660');
const url = ref('');
const comment = ref('');
const comments = ref<Comment[]>([]);
onMounted(() => {
// get target url from query param 'url'
const urlParams = new URLSearchParams(window.location.search);
const urlParam = urlParams.get('url');
if (urlParam) {
url.value = urlParam;
}
});
watch(url, (newVal) => {
if (newVal) {
getComments();
}
});
function getComments() {
fetch(`${BACKEND_URL}/api/v1/comments?url=${url.value}`)
.then((res) => res.json())
.then((data) => {
if (!!data) {
comments.value = data;
}
console.log(data);
});
}
function handleSubmit(e: Event) {
e.preventDefault();
fetch(`${BACKEND_URL}/api/v1/comment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
url: url.value,
comment: comment.value,
user_id: 'u_12345'
}),
})
.then((res) => {
if (res.ok) {
console.log('Comment submitted');
comment.value = '';
getComments();
}
}).catch((err) => {
console.error('Error:', err);
});
console.log('submit');
}
</script>
<template>
@ -18,13 +82,17 @@ const url = ref('https://vimeo.com/867950660');
<section class="comments">
<h2>Comments</h2>
<form class="comment-form">
<textarea placeholder="Add a comment..."></textarea>
<form class="comment-form" v-on:submit="handleSubmit">
<textarea placeholder="Add a comment..." v-model="comment"></textarea>
<button type="submit">Submit</button>
</form>
<div v-for="i in 5" :key="i">
<CommentComponent />
<div v-for="(remark, i) in comments" :key="i">
<CommentComponent :content="remark.content" :avatar="`https://cdn.vuetifyjs.com/images/lists/1.jpg`" />
</div>
<div v-if="comments.length === 0">
<p>No comments yet.</p>
</div>
</section>