Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

made short.io importer work

Steven Tey18cd80820632
diff --git a/app/api/cron/import/bitly/route.ts b/app/api/cron/import/bitly/route.ts
new file mode 100644
index 0000000000..8cba536333
--- /dev/null
+++ b/app/api/cron/import/bitly/route.ts
@@ -0,0 +1,79 @@
+import { log } from "#/lib/utils";
+import { importLinksFromBitly } from "./utils";
+import { redis } from "#/lib/upstash";
+import { NextResponse } from "next/server";
+import prisma from "#/lib/prisma";
+import { randomBadgeColor } from "@/components/app/links/tag-badge";
+import { receiver } from "#/lib/cron/utils";
+
+export async function POST(req: Request) {
+ const body = await req.json();
+ if (process.env.VERCEL === "1") {
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
+ try {
+ const { projectId, bitlyGroup, keepTags } = body;
+ const bitlyApiKey = await redis.get(`import:bitly:${projectId}`);
+ let tagsToId;
+ if (keepTags === true) {
+ const tags = await fetch(
+ `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/tags`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${bitlyApiKey}`,
+ },
+ },
+ )
+ .then((r) => r.json())
+ .then((r) => r.tags);
+
+ await prisma.tag.createMany({
+ data: tags.map((tag) => ({
+ name: tag,
+ color: randomBadgeColor(),
+ projectId,
+ })),
+ skipDuplicates: true,
+ });
+ tagsToId = await prisma.tag
+ .findMany({
+ where: {
+ projectId,
+ },
+ select: {
+ id: true,
+ name: true,
+ },
+ })
+ .then((tags) =>
+ tags.reduce((acc, tag) => {
+ acc[tag.name] = tag.id;
+ return acc;
+ }, {}),
+ );
+ }
+ await importLinksFromBitly({
+ ...body,
+ tagsToId,
+ bitlyApiKey,
+ });
+ return NextResponse.json({
+ response: "success",
+ });
+ } catch (error) {
+ await log({
+ message: "Import Bitly cron failed. Error: " + error.message,
+ type: "cron",
+ mention: true,
+ });
+ return NextResponse.json({ error: error.message });
+ }
+}
diff --git a/app/api/cron/import/utils.ts b/app/api/cron/import/bitly/utils.ts
similarity index 99%
rename from app/api/cron/import/utils.ts
rename to app/api/cron/import/bitly/utils.ts
index 9f5cb27dfa..422c63cf2a 100644
--- a/app/api/cron/import/utils.ts
+++ b/app/api/cron/import/bitly/utils.ts
@@ -66,7 +66,7 @@ export const importLinksFromBitly = async ({
...(tagId ? { tagId } : {}),
};
})
- .filter((link) => link !== null);
+ .filter(Boolean);
// import links into database
await Promise.all([
diff --git a/app/api/cron/import/route.ts b/app/api/cron/import/route.ts
deleted file mode 100644
index 0b92c7a18f..0000000000
--- a/app/api/cron/import/route.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { log } from "#/lib/utils";
-import { importLinksFromBitly } from "./utils";
-import { redis } from "#/lib/upstash";
-import { NextResponse } from "next/server";
-import { Receiver } from "@upstash/qstash";
-import prisma from "#/lib/prisma";
-import { randomBadgeColor } from "@/components/app/links/tag-badge";
-
-const receiver = new Receiver({
- currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY || "",
- nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY || "",
-});
-
-export async function POST(req: Request) {
- const body = await req.json();
- if (process.env.VERCEL === "1") {
- const isValid = await receiver.verify({
- signature: req.headers.get("Upstash-Signature") || "",
- body: JSON.stringify(body),
- });
- if (!isValid) {
- return new Response("Unauthorized", { status: 401 });
- }
- }
-
- try {
- const { provider, projectId, bitlyGroup, keepTags } = body;
- if (provider === "bitly") {
- const bitlyApiKey = await redis.get(`import:bitly:${projectId}`);
- let tagsToId;
- if (keepTags === true) {
- const tags = await fetch(
- `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/tags`,
- {
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${bitlyApiKey}`,
- },
- },
- )
- .then((r) => r.json())
- .then((r) => r.tags);
-
- await prisma.tag.createMany({
- data: tags.map((tag) => ({
- name: tag,
- color: randomBadgeColor(),
- projectId,
- })),
- skipDuplicates: true,
- });
- tagsToId = await prisma.tag
- .findMany({
- where: {
- projectId,
- },
- select: {
- id: true,
- name: true,
- },
- })
- .then((tags) =>
- tags.reduce((acc, tag) => {
- acc[tag.name] = tag.id;
- return acc;
- }, {}),
- );
- }
- await importLinksFromBitly({
- ...body,
- tagsToId,
- bitlyApiKey,
- });
- }
- return NextResponse.json({
- response: "success",
- });
- } catch (error) {
- await log({
- message: "Import cron failed. Error: " + error.message,
- type: "cron",
- mention: true,
- });
- return NextResponse.json({ error: error.message });
- }
-}
diff --git a/app/api/cron/import/short/route.ts b/app/api/cron/import/short/route.ts
new file mode 100644
index 0000000000..85dd374582
--- /dev/null
+++ b/app/api/cron/import/short/route.ts
@@ -0,0 +1,43 @@
+import { log } from "#/lib/utils";
+import { redis } from "#/lib/upstash";
+import { NextResponse } from "next/server";
+import prisma from "#/lib/prisma";
+import { randomBadgeColor } from "@/components/app/links/tag-badge";
+import { receiver } from "#/lib/cron/utils";
+import { importLinksFromShort } from "./utils";
+
+export async function POST(req: Request) {
+ const body = await req.json();
+ if (process.env.VERCEL === "1") {
+ const isValid = await receiver.verify({
+ signature: req.headers.get("Upstash-Signature") || "",
+ body: JSON.stringify(body),
+ });
+ if (!isValid) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ }
+
+ try {
+ const { projectId, domainId, domain } = body;
+ const shortApiKey = (await redis.get(
+ `import:short:${projectId}`,
+ )) as string;
+ await importLinksFromShort({
+ projectId,
+ domainId,
+ domain,
+ shortApiKey,
+ });
+ return NextResponse.json({
+ response: "success",
+ });
+ } catch (error) {
+ await log({
+ message: "Import Short.io cron failed. Error: " + error.message,
+ type: "cron",
+ mention: true,
+ });
+ return NextResponse.json({ error: error.message });
+ }
+}
diff --git a/app/api/cron/import/short/utils.ts b/app/api/cron/import/short/utils.ts
new file mode 100644
index 0000000000..589ec570d3
--- /dev/null
+++ b/app/api/cron/import/short/utils.ts
@@ -0,0 +1,161 @@
+import prisma from "#/lib/prisma";
+import { redis } from "#/lib/upstash";
+import { sendEmail } from "emails";
+import LinksImported from "emails/links-imported";
+
+// recursive function to check if nextPageToken is not null, else break
+export const importLinksFromShort = async ({
+ projectId,
+ domainId,
+ domain,
+ shortApiKey,
+ pageToken = null,
+ count = 0,
+}: {
+ projectId: string;
+ domainId: number;
+ domain: string;
+ shortApiKey: string;
+ pageToken?: string | null;
+ count?: number;
+}) => {
+ const data = await fetch(
+ `https://api.short.io/api/links?domain_id=${domainId}&limit=150${
+ pageToken ? `&pageToken=${pageToken}` : ""
+ }`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: shortApiKey,
+ },
+ },
+ ).then((res) => res.json());
+ const { links, nextPageToken } = data;
+
+ // const pipeline = redis.pipeline();
+
+ // convert links to format that can be imported into database
+ const importedLinks = links
+ .map((link) => {
+ const {
+ originalURL,
+ path,
+ title,
+ expiresAt,
+ iphoneURL,
+ androidURL,
+ archived,
+ createdAt,
+ } = link;
+ // skip the root domain
+ if (path.length === 0) {
+ return null;
+ }
+ // pipeline.set(
+ // `${domain}:${path}`,
+ // {
+ // url: encodeURIComponent(originalURL),
+ // ...(iphoneURL && { ios: encodeURIComponent(iphoneURL) }),
+ // ...(androidURL && { android: encodeURIComponent(androidURL) }),
+ // },
+ // );
+ return {
+ projectId,
+ domain,
+ key: path,
+ url: originalURL,
+ title,
+ // convert unix timestamp in milliseconds to DateTime toISOString
+ expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
+ ios: iphoneURL,
+ android: androidURL,
+ archived,
+ createdAt,
+ };
+ })
+ .filter(Boolean);
+
+ // import links into database
+ await Promise.all([
+ prisma.link.createMany({
+ data: importedLinks,
+ skipDuplicates: true,
+ }),
+ // pipeline.exec(),
+ ]);
+
+ count += importedLinks.length;
+
+ console.log({
+ importedLinksLength: importedLinks.length,
+ count,
+ nextPageToken,
+ });
+
+ // wait 500 ms before making another request
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ if (!nextPageToken) {
+ const project = await prisma.project.findUnique({
+ where: {
+ id: projectId,
+ },
+ select: {
+ name: true,
+ slug: true,
+ users: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ user: {
+ select: {
+ email: true,
+ },
+ },
+ },
+ },
+ links: {
+ select: {
+ domain: true,
+ key: true,
+ createdAt: true,
+ },
+ take: 5,
+ },
+ },
+ });
+ const ownerEmail = project?.users[0].user.email ?? "";
+ const links = project?.links ?? [];
+
+ await Promise.all([
+ // delete key from redis
+ redis.del(`import:short:${projectId}`),
+
+ // send email to user
+ sendEmail({
+ subject: `Your Short.io links have been imported!`,
+ email: ownerEmail,
+ react: LinksImported({
+ email: ownerEmail,
+ provider: "Short.io",
+ count,
+ links,
+ domains: [domain],
+ projectName: project?.name ?? "",
+ projectSlug: project?.slug ?? "",
+ }),
+ }),
+ ]);
+ return count;
+ } else {
+ return await importLinksFromShort({
+ projectId,
+ domainId,
+ domain,
+ shortApiKey,
+ pageToken: nextPageToken,
+ count,
+ });
+ }
+};
diff --git a/components/app/modals/import-short-modal.tsx b/components/app/modals/import-short-modal.tsx
index e0e872ae92..7758660cab 100644
--- a/components/app/modals/import-short-modal.tsx
+++ b/components/app/modals/import-short-modal.tsx
@@ -9,7 +9,6 @@ import {
useState,
} from "react";
import Modal from "#/ui/modal";
-import useProject from "#/lib/swr/use-project";
import Switch from "#/ui/switch";
import Button from "#/ui/button";
import { toast } from "sonner";
@@ -17,9 +16,10 @@ import { ArrowRight } from "lucide-react";
import { Logo, LoadingSpinner } from "#/ui/icons";
import { ModalContext } from "#/ui/modal-provider";
import useSWR, { mutate } from "swr";
-import { BitlyGroupProps } from "#/lib/types";
-import Tooltip from "#/ui/tooltip";
-import { fetcher } from "#/lib/utils";
+import { ShortioDomainProps } from "#/lib/types";
+import Tooltip, { InfoTooltip, SimpleTooltipContent } from "#/ui/tooltip";
+import { fetcher, nFormatter } from "#/lib/utils";
+import { HOME_DOMAIN } from "#/lib/constants";
function ImportShortModal({
showImportShortModal,
@@ -28,13 +28,10 @@ function ImportShortModal({
showImportShortModal: boolean;
setShowImportShortModal: Dispatch<SetStateAction<boolean>>;
}) {
- const { id: projectId } = useProject();
const router = useRouter();
const { slug, import: importSource } = router.query;
- const [redirecting, setRedirecting] = useState(false);
-
- const { data: groups, isLoading } = useSWR<BitlyGroupProps[]>(
+ const { data: domains, isLoading } = useSWR<ShortioDomainProps[]>(
slug && `/api/projects/${slug}/import/short`,
fetcher,
{
@@ -44,13 +41,11 @@ function ImportShortModal({
},
);
- const [selectedDomains, setSelectedDomains] = useState<
- {
- domain: string;
- bitlyGroup: string;
- }[]
- >([]);
- const [selectedGroupTags, setSelectedGroupTags] = useState<string[]>([]);
+ const [submitting, setSubmitting] = useState(false);
+
+ const [selectedDomains, setSelectedDomains] = useState<ShortioDomainProps[]>(
+ [],
+ );
const [importing, setImporting] = useState(false);
const { setPollLinks } = useContext(ModalContext);
@@ -87,7 +82,7 @@ function ImportShortModal({
<div className="flex items-center space-x-3 py-4">
<img
src="/_static/icons/short.svg"
- alt="Bitly logo"
+ alt="Short.io logo"
className="h-10 w-10"
/>
<ArrowRight className="h-5 w-5 text-gray-600" />
@@ -104,22 +99,21 @@ function ImportShortModal({
{isLoading ? (
<button className="flex flex-col items-center justify-center space-y-4 bg-none">
<LoadingSpinner />
- <p className="text-sm text-gray-500">Connecting to Bitly</p>
+ <p className="text-sm text-gray-500">Connecting to Short.io</p>
</button>
- ) : groups ? (
+ ) : domains ? (
<form
onSubmit={async (e) => {
e.preventDefault();
setImporting(true);
toast.promise(
- fetch(`/api/projects/${slug}/import/bitly`, {
+ fetch(`/api/projects/${slug}/import/short`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
selectedDomains,
- selectedGroupTags,
}),
}).then((res) => {
setImporting(false);
@@ -142,44 +136,45 @@ function ImportShortModal({
className="flex flex-col space-y-4"
>
<div className="divide-y divide-gray-200">
- {groups.map(({ guid, bsds, tags }) => (
- <div key={guid} className="flex flex-col space-y-2">
+ {domains.map(({ id, domain, links }) => (
+ <div key={id} className="flex flex-col space-y-2">
<div className="flex items-center justify-between">
<p className="text-sm font-medium text-gray-700">Domains</p>
- <Tooltip content="Your Bitly group ID">
+ <Tooltip content="Your Short.io domain ID">
<p className="cursor-default text-xs uppercase text-gray-400 transition-colors hover:text-gray-700">
- {guid}
+ #{id}
</p>
</Tooltip>
</div>
- {bsds.map((bsd) => (
- <div
- key={bsd}
- className="flex items-center justify-between space-x-2 rounded-md border border-gray-200 bg-white px-4 py-2"
- >
- <p className="font-medium text-gray-800">{bsd}</p>
- <Switch
- fn={() => {
- const selected = isSelected(bsd);
- if (selected) {
- setSelectedDomains((prev) =>
- prev.filter((d) => d.domain !== bsd),
- );
- } else {
- setSelectedDomains((prev) => [
- ...prev,
- {
- domain: bsd,
- bitlyGroup: guid,
- },
- ]);
- }
- }}
- checked={isSelected(bsd)}
- />
+ <div className="flex items-center justify-between space-x-2 rounded-md border border-gray-200 bg-white px-4 py-2">
+ <div>
+ <p className="font-medium text-gray-800">{domain}</p>
+ <p className="text-xs text-gray-500">
+ {nFormatter(links)} links found
+ </p>
</div>
- ))}
- <div className="flex items-center justify-between space-x-2 rounded-md py-1 pl-2 pr-4">
+ <Switch
+ fn={() => {
+ const selected = isSelected(domain);
+ if (selected) {
+ setSelectedDomains((prev) =>
+ prev.filter((d) => d.domain !== domain),
+ );
+ } else {
+ setSelectedDomains((prev) => [
+ ...prev,
+ {
+ id,
+ domain,
+ links,
+ },
+ ]);
+ }
+ }}
+ checked={isSelected(domain)}
+ />
+ </div>
+ {/* <div className="flex items-center justify-between space-x-2 rounded-md py-1 pl-2 pr-4">
<p className="text-xs text-gray-500">
{tags.length} tags found. Import all?
</p>
@@ -195,7 +190,7 @@ function ImportShortModal({
}}
checked={selectedGroupTags.includes(guid)}
/>
- </div>
+ </div> */}
</div>
))}
</div>
@@ -207,7 +202,58 @@ function ImportShortModal({
</form>
) : (
// form to add API key to redis manually
- <form />
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setSubmitting(true);
+ fetch(`/api/projects/${slug}/import/short`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ apiKey: e.currentTarget.apiKey.value,
+ }),
+ }).then((res) => {
+ if (res.ok) {
+ mutate(`/api/projects/${slug}/import/short`);
+ toast.success("Successfully added API key");
+ } else {
+ toast.error("Error adding API key");
+ }
+ setSubmitting(false);
+ });
+ }}
+ className="flex flex-col space-y-4"
+ >
+ <div>
+ <div className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">
+ Short.io API Key
+ </h2>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title="Your Short.io API Key can be found in your Short.io account settings."
+ cta="Learn more."
+ href={`${HOME_DOMAIN}/help/article/import-from-short-io`}
+ />
+ }
+ />
+ </div>
+ <input
+ id="apiKey"
+ name="apiKey"
+ autoFocus
+ type="text"
+ placeholder="sk_xxxxxxxxxxxxxxxx"
+ autoComplete="off"
+ required
+ className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"
+ />
+ </div>
+ <Button text="Submit API Key" loading={submitting} />
+ </form>
)}
</div>
</Modal>
diff --git a/emails/links-imported.tsx b/emails/links-imported.tsx
index 62eb2379d2..2c3848cdea 100644
--- a/emails/links-imported.tsx
+++ b/emails/links-imported.tsx
@@ -126,14 +126,16 @@ export default function LinksImported({
))}
</Section>
)}
- <Section className="my-8 text-center">
- <Link
- className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
- href={`https://app.dub.sh/${projectSlug}`}
- >
- View {Intl.NumberFormat("en-us").format(count - 5)} more links
- </Link>
- </Section>
+ {links.length > 5 && (
+ <Section className="my-8 text-center">
+ <Link
+ className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
+ href={`https://app.dub.sh/${projectSlug}`}
+ >
+ View {Intl.NumberFormat("en-us").format(count - 5)} more links
+ </Link>
+ </Section>
+ )}
<Text className="text-sm leading-6 text-black">
If you haven't already{" "}
<Link
diff --git a/lib/cron/utils.ts b/lib/cron/utils.ts
index e8fd8eef81..07015e97b2 100644
--- a/lib/cron/utils.ts
+++ b/lib/cron/utils.ts
@@ -1,7 +1,19 @@
import Bottleneck from "bottleneck";
+import { Receiver } from "@upstash/qstash";
+import { Client } from "@upstash/qstash";
// we're using Bottleneck to avoid running into Resend's rate limit of 10 req/s
export const limiter = new Bottleneck({
maxConcurrent: 1, // maximum concurrent requests
minTime: 100, // minimum time between requests in ms
});
+
+// we're using Upstash's Receiver to verify the request signature
+export const receiver = new Receiver({
+ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY || "",
+ nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY || "",
+});
+
+export const qstash = new Client({
+ token: process.env.QSTASH_TOKEN || "",
+});
diff --git a/lib/types.ts b/lib/types.ts
index 1d2a050d8d..3a6aa7ff25 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -107,3 +107,9 @@ export interface BitlyGroupProps {
bsds: string[]; // custom domains
tags: string[];
}
+
+export interface ShortioDomainProps {
+ id: number;
+ domain: string;
+ links: number;
+}
diff --git a/pages/api/projects/[slug]/import/bitly.ts b/pages/api/projects/[slug]/import/bitly.ts
index 59833f2a0b..c0e70636fa 100644
--- a/pages/api/projects/[slug]/import/bitly.ts
+++ b/pages/api/projects/[slug]/import/bitly.ts
@@ -1,13 +1,9 @@
import { addDomainToVercel } from "#/lib/api/domains";
import { withProjectAuth } from "#/lib/auth";
+import { qstash } from "#/lib/cron/utils";
import prisma from "#/lib/prisma";
import { BitlyGroupProps } from "#/lib/types";
import { redis } from "#/lib/upstash";
-import { Client } from "@upstash/qstash";
-
-const qstash = new Client({
- token: process.env.QSTASH_TOKEN || "",
-});
export default withProjectAuth(async (req, res, project) => {
// get bitly groups and their respective domains
@@ -102,7 +98,7 @@ export default withProjectAuth(async (req, res, project) => {
? "https://app.dub.sh"
: process.env.NEXT_PUBLIC_VERCEL_ENV === "preview"
? "https://preview.dub.sh"
- : "https://067b-2600-1700-b5e4-b50-8197-b987-5375-e928.ngrok-free.app";
+ : process.env.NGROK_URL;
const response = await Promise.all(
groups
@@ -110,9 +106,8 @@ export default withProjectAuth(async (req, res, project) => {
.filter(({ domains }) => domains.length > 0)
.map(({ bitlyGroup, domains, keepTags }) =>
qstash.publishJSON({
- url: `${hostname}/api/cron/import`,
+ url: `${hostname}/api/cron/import/bitly`,
body: {
- provider: "bitly",
projectId: project.id,
bitlyGroup,
domains,
diff --git a/pages/api/projects/[slug]/import/short.ts b/pages/api/projects/[slug]/import/short.ts
new file mode 100644
index 0000000000..cd39bf8820
--- /dev/null
+++ b/pages/api/projects/[slug]/import/short.ts
@@ -0,0 +1,107 @@
+import { addDomainToVercel } from "#/lib/api/domains";
+import { withProjectAuth } from "#/lib/auth";
+import { qstash } from "#/lib/cron/utils";
+import prisma from "#/lib/prisma";
+import { ShortioDomainProps } from "#/lib/types";
+import { redis } from "#/lib/upstash";
+
+export default withProjectAuth(async (req, res, project) => {
+ // get Short.io domains and links count
+ if (req.method === "GET") {
+ const accessToken = await redis.get(`import:short:${project.id}`);
+ if (!accessToken) {
+ return res.status(200).end("No Short.io access token found");
+ }
+
+ const response = await fetch(`https://api.short.io/api/domains`, {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: accessToken as string,
+ },
+ });
+ const data = await response.json();
+ if (data.message === "FORBIDDEN") {
+ return res.status(403).end("Invalid Short.io access token");
+ }
+
+ const domains = await Promise.all(
+ data.map(async ({ id, hostname }: { id: number; hostname: string }) => ({
+ id,
+ domain: hostname,
+ links: await fetch(
+ `https://api-v2.short.cm/statistics/domain/${id}?period=total`,
+ {
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: accessToken as string,
+ },
+ },
+ )
+ .then((r) => r.json())
+ .then((data) => data.links - 1) // subtract 1 to exclude root domain
+ .catch((e) => 0),
+ })),
+ );
+
+ return res.status(200).json(domains);
+
+ // set the user's Short.io access token in Redis
+ } else if (req.method === "PUT") {
+ const { apiKey } = req.body;
+
+ const response = await redis.set(`import:short:${project.id}`, apiKey);
+ return res.status(200).json(response);
+
+ // create job to import links from Short.io
+ } else if (req.method === "POST") {
+ const { selectedDomains } = req.body as {
+ selectedDomains: ShortioDomainProps[];
+ };
+ console.log({
+ selectedDomains,
+ });
+
+ // check if there are domains that are not in the project
+ // if yes, add them to the project
+ const domainsNotInProject = selectedDomains.filter(
+ ({ domain }) => !project.domains?.find((d) => d.slug === domain),
+ );
+ if (domainsNotInProject.length > 0) {
+ await Promise.allSettled([
+ prisma.domain.createMany({
+ data: domainsNotInProject.map(({ domain }) => ({
+ slug: domain,
+ target: null,
+ type: "redirect",
+ projectId: project.id,
+ primary: false,
+ })),
+ skipDuplicates: true,
+ }),
+ domainsNotInProject.map(({ domain }) => addDomainToVercel(domain)),
+ ]);
+ }
+
+ const hostname =
+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
+ ? "https://app.dub.sh"
+ : process.env.NEXT_PUBLIC_VERCEL_ENV === "preview"
+ ? "https://preview.dub.sh"
+ : process.env.NGROK_URL;
+
+ const response = await Promise.all(
+ selectedDomains.map(({ id, domain }) =>
+ qstash.publishJSON({
+ url: `${hostname}/api/cron/import/short`,
+ body: {
+ projectId: project.id,
+ domainId: id,
+ domain,
+ },
+ }),
+ ),
+ );
+
+ return res.status(200).json(response);
+ }
+});
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index 024b788fbe..92f52c75ff 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -5,7 +5,6 @@ import AppLayout from "components/layout/app";
import useProject from "#/lib/swr/use-project";
import { useState } from "react";
import Popover from "#/ui/popover";
-import IconMenu from "@/components/shared/icon-menu";
import { ChevronDown, FilePlus2, Import } from "lucide-react";
import { useRouter } from "next/router";
@@ -24,12 +23,12 @@ export default function ProjectLinks() {
<MaxWidthWrapper>
<div className="flex items-center justify-between">
<h1 className="text-2xl text-gray-600">Links</h1>
- <div className="flex space-x-2">
+ <div className="flex">
<AddEditLinkButton />
<Popover
content={
- <div className="w-full p-2 md:w-52">
- <button
+ <div className="w-full p-2 md:w-44">
+ {/* <button
onClick={() => {}}
className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
>
@@ -37,24 +36,53 @@ export default function ProjectLinks() {
text="Bulk create links"
icon={<FilePlus2 className="h-4 w-4" />}
/>
- </button>
- <button
- onClick={() => {
- setOpenPopover(false);
- router.push({
- pathname: `/${slug}`,
- query: {
- import: "bitly",
- },
- });
- }}
- className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
- >
- <IconMenu
- text="Import from Bitly"
- icon={<Import className="h-4 w-4" />}
- />
- </button>
+ </button> */}
+ <div>
+ <div className="flex items-center space-x-2 p-2">
+ <Import className="h-4 w-4" />
+ <p className="text-xs font-medium uppercase text-gray-500">
+ Import Links
+ </p>
+ </div>
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ router.push({
+ pathname: `/${slug}`,
+ query: {
+ import: "bitly",
+ },
+ });
+ }}
+ className="flex w-full items-center space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
+ >
+ <img
+ src="/_static/icons/bitly.svg"
+ alt="Bitly logo"
+ className="h-4 w-4 rounded-full"
+ />
+ <p className="text-sm text-gray-600">Bitly</p>
+ </button>
+ <button
+ onClick={() => {
+ setOpenPopover(false);
+ router.push({
+ pathname: `/${slug}`,
+ query: {
+ import: "short",
+ },
+ });
+ }}
+ className="flex w-full items-center space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"
+ >
+ <img
+ src="/_static/icons/short.svg"
+ alt="Short.io logo"
+ className="h-4 w-4"
+ />
+ <p className="text-sm text-gray-600">Short.io</p>
+ </button>
+ </div>
</div>
}
openPopover={openPopover}
@@ -63,7 +91,7 @@ export default function ProjectLinks() {
>
<button
onClick={() => setOpenPopover(!openPopover)}
- className="group flex items-center justify-between space-x-2 rounded-md border border-gray-200 bg-white p-2.5 shadow transition-all duration-75 active:scale-95"
+ className="group ml-2 flex items-center justify-between space-x-2 rounded-md border border-gray-200 bg-white p-2.5 shadow transition-all duration-75 active:scale-95"
>
<ChevronDown
className={`h-4 w-4 shrink-0 ${