Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,9 @@ If your configuration is not valid, sqtracker will fail to start.
| SQ_BP_EARNED_PER_GB | envs | 1 | Number of bonus points awarded to a user for each GB they upload |
| SQ_BP_COST_PER_INVITE | envs | 3 | Number of bonus it costs a user to buy 1 invite (set to 0 to disable buying invites) |
| SQ_BP_COST_PER_GB | envs | 3 | Number of bonus it costs a user to buy 1 GB of upload (set to 0 to disable buying upload) |
| SQ_SITE_WIDE_FREELEECH | envs | `true` | Whether or not to enable freeleech on all torrents |
| SQ_SITE_WIDE_FREELEECH | envs | `false` | Whether or not to enable freeleech on all torrents |
| SQ_TORRENT_CATEGORIES | envs | `{ "Movies": ["HD", ...], "TV": [...] }` | A dictionary of categories, each with an array of zero or more sources available within that category |
| SQ_ALLOW_UNREGISTERED_VIEW | envs | `false` | Whether or not torrent pages can be viewed by unregistered users. If true, only logged in users will be able to download/interact, but anyone (search engines included) will be able to view/read torrent info. |
| SQ_BASE_URL | envs | https://demo.sqtracker.dev | The URL of your tracker site |
| SQ_API_URL | envs | https://demo.sqtracker.dev/api | The URL of your API. Under the recommended setup, it should be `${SQ_BASE_URL}/api` |
| SQ_MONGO_URL | envs | mongodb://sq_mongodb/sq | The URL of your MongoDB server. Under the recommended setup, it should be `mongodb://sq_mongodb/sq` |
Expand Down
9 changes: 9 additions & 0 deletions api/src/controllers/torrent.js
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,15 @@ export const listLatest = (tracker) => async (req, res, next) => {
}
};

export const listAll = async (req, res, next) => {
try {
const torrents = await Torrent.find({}, { infoHash: 1 }).lean();
res.json(torrents);
} catch (e) {
next(e);
}
};

export const searchTorrents = (tracker) => async (req, res, next) => {
const { query, category, source, tag, page } = req.query;
try {
Expand Down
2 changes: 1 addition & 1 deletion api/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ validateConfig(config).then(() => {
keyGenerator: (req) => {
if (
req.headers["x-forwarded-for"] &&
req.headers["x-sq-server-secret"] === process.env.SQ_SERVER_SECET
req.headers["x-sq-server-secret"] === process.env.SQ_SERVER_SECRET
)
return req.headers["x-forwarded-for"].split(",")[0];
return req.ip;
Expand Down
5 changes: 5 additions & 0 deletions api/src/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ const auth = async (req, res, next) => {
} catch (err) {
res.status(500).send(err);
}
} else if (
req.headers["x-sq-public-access"] === "true" &&
req.headers["x-sq-server-secret"] === process.env.SQ_SERVER_SECRET
) {
next();
} else {
res.sendStatus(401);
}
Expand Down
2 changes: 2 additions & 0 deletions api/src/routes/torrent.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
deleteTorrent,
fetchTorrent,
listLatest,
listAll,
removeVote,
searchTorrents,
toggleFreeleech,
Expand All @@ -28,6 +29,7 @@ export default (tracker) => {
router.post("/toggle-freeleech/:infoHash", toggleFreeleech);
router.post("/bookmark/:infoHash", toggleBookmark);
router.get("/latest", listLatest(tracker));
router.get("/all", listAll);
router.get("/search", searchTorrents(tracker));
return router;
};
1 change: 1 addition & 0 deletions api/src/utils/validateConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const configSchema = yup
}, {});
return yup.object(entries).required();
}),
SQ_ALLOW_UNREGISTERED_VIEW: yup.boolean().required(),
SQ_BASE_URL: yup.string().matches(httpRegex).required(),
SQ_API_URL: yup.string().matches(httpRegex).required(),
SQ_MONGO_URL: yup.string().matches(mongoRegex).required(),
Expand Down
1 change: 1 addition & 0 deletions client/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ export const getServerSideProps = withAuthServerSideProps(
return { props: {} };
}
},
false,
true
);

Expand Down
56 changes: 56 additions & 0 deletions client/pages/sitemap.xml.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import getConfig from "next/config";

const Sitemap = () => {};

export const getServerSideProps = async ({ req, res }) => {
const {
publicRuntimeConfig: {
SQ_BASE_URL,
SQ_API_URL,
SQ_ALLOW_UNREGISTERED_VIEW,
},
serverRuntimeConfig: { SQ_SERVER_SECRET },
} = getConfig();

const urls = [SQ_BASE_URL, `${SQ_BASE_URL}/login`, `${SQ_BASE_URL}/register`];

if (SQ_ALLOW_UNREGISTERED_VIEW) {
try {
const listRes = await fetch(`${SQ_API_URL}/torrent/all`, {
headers: {
"Content-Type": "application/json",
"X-Forwarded-For":
req.headers["x-forwarded-for"] ?? req.socket.remoteAddress,
"X-Sq-Server-Secret": SQ_SERVER_SECRET,
"X-Sq-Public-Access": true,
},
});
const torrents = await listRes.json();
for (const { infoHash } of torrents) {
urls.push(`${SQ_BASE_URL}/torrent/${infoHash}`);
}
} catch (e) {
console.error(`[sq] could not list torrents: ${e}`);
}
}

const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls
.map(
(url) => `<url>
<loc>${url}</loc>
</url>`
)
.join("\n")}
</urlset>
`;

res.setHeader("Content-Type", "text/xml");
res.write(sitemap);
res.end();

return { props: {} };
};

export default Sitemap;
129 changes: 86 additions & 43 deletions client/pages/torrent/[infoHash].js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
const [comments, setComments] = useState(torrent.comments);
const [isFreeleech, setIsFreeleech] = useState(torrent.freeleech);
const [hasGroup, setHasGroup] = useState(!!torrent.group);
const [bookmarked, setBookmarked] = useState(torrent.fetchedBy.bookmarked);
const [bookmarked, setBookmarked] = useState(torrent.fetchedBy?.bookmarked);

const { addNotification } = useContext(NotificationContext);
const { setLoading } = useContext(LoadingContext);
Expand Down Expand Up @@ -477,9 +477,20 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
)}
</Text>
<Box display="flex" alignItems="center" ml={3}>
<Button onClick={handleBookmark} variant="secondary" px="10px" mr={3}>
{bookmarked ? <Bookmark size={18} /> : <BookmarkEmpty size={18} />}
</Button>
{!!userId && (
<Button
onClick={handleBookmark}
variant="secondary"
px="10px"
mr={3}
>
{bookmarked ? (
<Bookmark size={18} />
) : (
<BookmarkEmpty size={18} />
)}
</Button>
)}
{(userRole === "admin" || userId === torrent.uploadedBy._id) && (
<>
<Button
Expand All @@ -503,13 +514,19 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
{isFreeleech ? "Unset" : "Set"} freeleech
</Button>
)}
<Button
as="a"
href={`${SQ_API_URL}/torrent/download/${torrent.infoHash}/${uid}`}
target="_blank"
>
Download .torrent
</Button>
{!!userId ? (
<Button
as="a"
href={`${SQ_API_URL}/torrent/download/${torrent.infoHash}/${uid}`}
target="_blank"
>
Download .torrent
</Button>
) : (
<Link href="/login" passHref>
<Button as="a">Log in to download</Button>
</Link>
)}
</Box>
</Box>
<Info
Expand Down Expand Up @@ -629,29 +646,43 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
display="flex"
borderBottom="1px solid"
borderColor="border"
pb={5}
pb={userId ? 5 : 0}
mb={5}
>
<Button onClick={() => handleVote("up")} variant="noBackground" mr={2}>
<Text icon={Like} iconColor={userVote === "up" ? "green" : undefined}>
{votes.up || 0}
</Text>
</Button>
<Button
onClick={() => handleVote("down")}
variant="noBackground"
mr={2}
>
<Text
icon={Dislike}
iconColor={userVote === "down" ? "red" : undefined}
>
{votes.down || 0}
</Text>
</Button>
<Button onClick={() => setShowReportModal(true)} variant="noBackground">
Report
</Button>
{!!userId && (
<>
<Button
onClick={() => handleVote("up")}
variant="noBackground"
mr={2}
>
<Text
icon={Like}
iconColor={userVote === "up" ? "green" : undefined}
>
{votes.up || 0}
</Text>
</Button>
<Button
onClick={() => handleVote("down")}
variant="noBackground"
mr={2}
>
<Text
icon={Dislike}
iconColor={userVote === "down" ? "red" : undefined}
>
{votes.down || 0}
</Text>
</Button>
<Button
onClick={() => setShowReportModal(true)}
variant="noBackground"
>
Report
</Button>
</>
)}
</Box>
<Box borderBottom="1px solid" borderColor="border" pb={5} mb={5}>
<Box
Expand All @@ -674,11 +705,13 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
Remove this torrent
</Button>
)}
<Link href={`/upload?groupWith=${torrent.infoHash}`} passHref>
<Button as="a" ml={3}>
Add a torrent
</Button>
</Link>
{!!userId && (
<Link href={`/upload?groupWith=${torrent.infoHash}`} passHref>
<Button as="a" ml={3}>
Add a torrent
</Button>
</Link>
)}
</Box>
</Box>
{torrent.groupTorrents.length && hasGroup ? (
Expand All @@ -693,15 +726,16 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
<Text as="h2" mb={4}>
Comments
</Text>
<form onSubmit={handleComment}>
<form onSubmit={userId ? handleComment : undefined}>
<Input
ref={commentInputRef}
name="comment"
label="Post a comment"
rows="5"
disabled={!userId}
mb={4}
/>
<Button display="block" ml="auto">
<Button disabled={!userId} display="block" ml="auto">
Post
</Button>
</form>
Expand Down Expand Up @@ -780,15 +814,23 @@ const Torrent = ({ token, torrent = {}, userId, userRole, uid }) => {
};

export const getServerSideProps = withAuthServerSideProps(
async ({ token, userId, fetchHeaders, query: { infoHash } }) => {
if (!token) return { props: {} };
async ({
token,
userId,
fetchHeaders,
isPublicAccess,
query: { infoHash },
}) => {
if (!token && !isPublicAccess) return { props: {} };

const {
publicRuntimeConfig: { SQ_API_URL },
serverRuntimeConfig: { SQ_JWT_SECRET },
} = getConfig();

const { id, role } = jwt.verify(token, SQ_JWT_SECRET);
const { id, role } = token
? jwt.verify(token, SQ_JWT_SECRET)
: { id: null, role: null };

try {
const torrentRes = await fetch(`${SQ_API_URL}/torrent/info/${infoHash}`, {
Expand All @@ -810,7 +852,8 @@ export const getServerSideProps = withAuthServerSideProps(
if (e === "banned") throw "banned";
return { props: {} };
}
}
},
true
);

export default Torrent;
30 changes: 22 additions & 8 deletions client/utils/withAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,39 +30,53 @@ export const withAuth = (Component, noRedirect = false) => {

export const withAuthServerSideProps = (
getServerSideProps,
publicAccess = false,
noRedirect = false
) => {
return async (ctx) => {
const { token, userId } = getReqCookies(ctx.req);
let { token, userId } = getReqCookies(ctx.req);

if (!token && !noRedirect)
const {
serverRuntimeConfig: { SQ_SERVER_SECRET },
publicRuntimeConfig: { SQ_ALLOW_UNREGISTERED_VIEW },
} = getConfig();

const isPublicAccess = publicAccess && SQ_ALLOW_UNREGISTERED_VIEW && !token;

if (!token && !noRedirect && !isPublicAccess)
return {
redirect: {
permanent: false,
destination: "/login",
},
};

if (!token && noRedirect) return { props: {} };
if (!token && noRedirect && !isPublicAccess) return { props: {} };

try {
const {
serverRuntimeConfig: { SQ_SERVER_SECRET },
} = getConfig();
if (isPublicAccess) {
token = null;
userId = null;
}

try {
const fetchHeaders = {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
"X-Forwarded-For":
ctx.req.headers["x-forwarded-for"] ?? ctx.req.socket.remoteAddress,
"X-Sq-Server-Secret": SQ_SERVER_SECRET,
"X-Sq-Public-Access": isPublicAccess,
};

if (token) {
fetchHeaders["Authorization"] = `Bearer ${token}`;
}

const { props: ssProps } = await getServerSideProps({
...ctx,
token,
userId,
fetchHeaders,
isPublicAccess,
});
return { props: { ...ssProps, token } };
} catch (e) {
Expand Down
Loading