The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
added option to keep tags from Bitly
Steven Tey94c2051a5f76
diff --git a/app/api/callback/bitly/route.ts b/app/api/callback/bitly/route.tsindex 2ea456f87a..271d3f9d6c 100644--- a/app/api/callback/bitly/route.ts+++ b/app/api/callback/bitly/route.ts@@ -1,9 +1,15 @@import { NextResponse } from "next/server";+import prisma from "#/lib/prisma";+import { redis } from "#/lib/upstash";export async function GET(req: Request) {const { searchParams } = new URL(req.url);++ // get code and project id from query paramsconst code = searchParams.get("code") as string;+ const projectId = searchParams.get("state") as string;+ // get access token from bitlyconst response = await fetch("https://api-ssl.bitly.com/oauth/access_token", {method: "POST",headers: {@@ -12,10 +18,38 @@ export async function GET(req: Request) {body: `client_id=${process.env.NEXT_PUBLIC_BITLY_CLIENT_ID}&client_secret=${process.env.BITLY_CLIENT_SECRET}&code=${code}&redirect_uri=${process.env.NEXT_PUBLIC_BITLY_REDIRECT_URI}`,}).then((r) => r.text());+ if (!response || response.includes("error")) {+ return NextResponse.redirect(+ `${+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "https://app.dub.sh/"+ : "http://app.localhost:3000/"+ }`,+ );+ }+const params = new URLSearchParams(response);- console.log({- access_token: params.get("access_token"),- });- return NextResponse.redirect("http://app.localhost:3000/vercel");+ const [project, _] = await Promise.all([+ // get project slug from projectId+ prisma.project.findUnique({+ where: {+ id: projectId,+ },+ select: {+ slug: true,+ },+ }),+ // store access token in redis+ redis.set(`import:bitly:${projectId}`, params.get("access_token")),+ ]);++ // redirect to project page with import query param+ return NextResponse.redirect(+ `${+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "https://app.dub.sh/"+ : "http://app.localhost:3000/"+ }${project ? `${project.slug}?import=bitly` : ""}`,+ );}diff --git a/app/api/cron/import/route.ts b/app/api/cron/import/route.tsnew file mode 100644index 0000000000..8b2fd2069f--- /dev/null+++ b/app/api/cron/import/route.ts@@ -0,0 +1,44 @@+import { log } from "#/lib/utils";+import { importLinksFromBitly } from "#/lib/cron/import";+import { redis } from "#/lib/upstash";+import { NextResponse } from "next/server";+import { Receiver } from "@upstash/qstash";++export const receiver = new Receiver({+ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY || "",+ nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY || "",+});++export async function POST(req: Request) {+ if (process.env.NODE_ENV === "production") {+ const isValid = await receiver.verify({+ signature: req.headers.get("Upstash-Signature") || "",+ body: "",+ });+ if (!isValid) {+ return new Response("Unauthorized", { status: 401 });+ }+ }++ try {+ const data = await req.json();+ const { provider, projectId } = data;+ if (provider === "bitly") {+ const bitlyApiKey = await redis.get(`import:bitly:${projectId}`);+ await importLinksFromBitly({+ ...data,+ 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/dub.sh/metatags/content.tsx b/app/dub.sh/metatags/content.tsxindex 6e197f9fbe..39c369fc6c 100644--- a/app/dub.sh/metatags/content.tsx+++ b/app/dub.sh/metatags/content.tsx@@ -130,7 +130,7 @@ export default function MetatagsContent() {</span></button>- <pre className="overflow-auto rounded-md border border-gray-400 bg-stone-800 p-5 text-left">+ <pre className="overflow-auto rounded-md border border-gray-400 bg-gray-800 p-5 text-left"><code className="text-xs text-white">{JSON.stringify({diff --git a/app/providers.tsx b/app/providers.tsxindex 7c3829fcfb..6856fbe337 100644--- a/app/providers.tsx+++ b/app/providers.tsx@@ -7,7 +7,7 @@ import { Analytics } from "@vercel/analytics/react";export default function Providers({ children }: { children: ReactNode }) {return (<>- <Toaster />+ <Toaster closeButton />{children}<Analytics /></>diff --git a/app/ui/button.tsx b/app/ui/button.tsxindex edd1384791..f6c6861d93 100644--- a/app/ui/button.tsx+++ b/app/ui/button.tsx@@ -1,6 +1,6 @@"use client";-import { LoadingDots } from "#/ui/icons";+import { LoadingSpinner } from "#/ui/icons";import Tooltip from "#/ui/tooltip";import { cn } from "#/lib/utils";import { ReactNode } from "react";@@ -36,7 +36,7 @@ export default function Button({// if onClick is passed, it's a "button" type, otherwise it's being used in a form, hence "submit"type={onClick ? "button" : "submit"}className={cn(- "flex h-10 w-full items-center justify-center space-x-2 rounded-md border text-sm transition-all focus:outline-none",+ "flex h-10 w-full items-center justify-center space-x-2 rounded-md border px-4 text-sm transition-all focus:outline-none",disabled || loading? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400": {@@ -51,14 +51,8 @@ export default function Button({{...(onClick ? { onClick } : {})}disabled={disabled || loading}>- {loading ? (- <LoadingDots color="#808080" />- ) : (- <>- {icon}- <p>{text}</p>- </>- )}+ {loading ? <LoadingSpinner /> : icon ? icon : null}+ <p>{text}</p></button>);}diff --git a/app/ui/form.tsx b/app/ui/form.tsxindex 88a135301c..385b1438df 100644--- a/app/ui/form.tsx+++ b/app/ui/form.tsx@@ -53,7 +53,7 @@ export default function Form({<div className="flex items-center justify-between rounded-b-lg border-t border-gray-200 bg-gray-50 p-3 sm:px-10"><p className="text-sm text-gray-500">{helpText}</p>- <div className="w-32">+ <div><Buttontext="Save Changes"loading={saving}diff --git a/app/ui/icons/loading-spinner.module.css b/app/ui/icons/loading-spinner.module.cssindex 2b1ac0afe4..3504c36d2c 100644--- a/app/ui/icons/loading-spinner.module.css+++ b/app/ui/icons/loading-spinner.module.css@@ -1,74 +1,67 @@.spinner {- color: gray;- display: inline-block;position: relative;- width: 70px;- height: 70px;- transform: scale(0.3) translateX(-90px) translateY(-5px);+ top: 50%;+ left: 50%;}.spinner div {- transform-origin: 40px 40px;animation: spinner 1.2s linear infinite;-}-.spinner div:after {- content: " ";- display: block;+ background: gray;position: absolute;- top: 5px;- left: 37px;- width: 6px;- height: 20px;- border-radius: 20%;- background: black;+ border-radius: 1rem;+ width: 30%;+ height: 8%;+ left: -10%;+ top: -4%;}.spinner div:nth-child(1) {- transform: rotate(0deg);- animation-delay: -1.1s;+ animation-delay: -1.2s;+ transform: rotate(1deg) translate(120%);}.spinner div:nth-child(2) {- transform: rotate(30deg);- animation-delay: -1s;+ animation-delay: -1.1s;+ transform: rotate(30deg) translate(120%);}.spinner div:nth-child(3) {- transform: rotate(60deg);- animation-delay: -0.9s;+ animation-delay: -1s;+ transform: rotate(60deg) translate(120%);}.spinner div:nth-child(4) {- transform: rotate(90deg);- animation-delay: -0.8s;+ animation-delay: -0.9s;+ transform: rotate(90deg) translate(120%);}.spinner div:nth-child(5) {- transform: rotate(120deg);- animation-delay: -0.7s;+ animation-delay: -0.8s;+ transform: rotate(120deg) translate(120%);}.spinner div:nth-child(6) {- transform: rotate(150deg);- animation-delay: -0.6s;+ animation-delay: -0.7s;+ transform: rotate(150deg) translate(120%);}.spinner div:nth-child(7) {- transform: rotate(180deg);- animation-delay: -0.5s;+ animation-delay: -0.6s;+ transform: rotate(180deg) translate(120%);}.spinner div:nth-child(8) {- transform: rotate(210deg);- animation-delay: -0.4s;+ animation-delay: -0.5s;+ transform: rotate(210deg) translate(120%);}.spinner div:nth-child(9) {- transform: rotate(240deg);- animation-delay: -0.3s;+ animation-delay: -0.4s;+ transform: rotate(240deg) translate(120%);}.spinner div:nth-child(10) {- transform: rotate(270deg);- animation-delay: -0.2s;+ animation-delay: -0.3s;+ transform: rotate(270deg) translate(120%);}.spinner div:nth-child(11) {- transform: rotate(300deg);- animation-delay: -0.1s;+ animation-delay: -0.2s;+ transform: rotate(300deg) translate(120%);}.spinner div:nth-child(12) {- transform: rotate(330deg);- animation-delay: 0s;+ animation-delay: -0.1s;+ transform: rotate(330deg) translate(120%);}+@keyframes spinner {0% {opacity: 1;diff --git a/app/ui/icons/loading-spinner.tsx b/app/ui/icons/loading-spinner.tsxindex 1c8e704aa4..f5a24c8007 100644--- a/app/ui/icons/loading-spinner.tsx+++ b/app/ui/icons/loading-spinner.tsx@@ -1,20 +1,14 @@+import { cn } from "#/lib/utils";import styles from "./loading-spinner.module.css";-export default function LoadingSpinner() {+export default function LoadingSpinner({ className }: { className?: string }) {return (- <div className={styles.spinner}>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>- <div></div>+ <div className={cn("h-5 w-5", className)}>+ <div className={cn(styles.spinner, "h-5 w-5", className)}>+ {[...Array(12)].map((_, i) => (+ <div key={i} />+ ))}+ </div></div>);}diff --git a/app/ui/modal-provider.tsx b/app/ui/modal-provider.tsxindex bb080c3f86..7a674a3df8 100644--- a/app/ui/modal-provider.tsx+++ b/app/ui/modal-provider.tsx@@ -6,6 +6,7 @@ import {SetStateAction,createContext,useEffect,+ useState,} from "react";import { useSession } from "next-auth/react";import ErrorPage from "next/error";@@ -17,17 +18,22 @@ import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modalimport { useImportLinksModal } from "@/components/app/modals/import-links-modal";import { useAddEditDomainModal } from "@/components/app/modals/add-edit-domain-modal";import { useGoogleOauthModal } from "@/components/app/modals/google-oauth-modal";+import { mutate } from "swr";+import { useRouter } from "next/router";+import { getQueryString } from "#/lib/utils";export const ModalContext = createContext<{setShowAddProjectModal: Dispatch<SetStateAction<boolean>>;setShowAddEditDomainModal: Dispatch<SetStateAction<boolean>>;setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;setShowImportLinksModal: Dispatch<SetStateAction<boolean>>;+ setPollLinks: Dispatch<SetStateAction<boolean>>;}>({setShowAddProjectModal: () => {},setShowAddEditDomainModal: () => {},setShowAddEditLinkModal: () => {},setShowImportLinksModal: () => {},+ setPollLinks: () => {},});export default function ModalProvider({ children }: { children: ReactNode }) {@@ -44,6 +50,28 @@ export default function ModalProvider({ children }: { children: ReactNode }) {const { error, loading } = useProject();const { data: session } = useSession();+ const router = useRouter();++ const [pollLinks, setPollLinks] = useState(false);+ useEffect(() => {+ if (pollLinks) {+ // if pollLinks is true, start polling links endpoint every 500 ms (stop after 30 seconds)+ const pollingInterval = setInterval(() => {+ mutate(`/api/links${getQueryString(router)}`);+ mutate(+ (key) =>+ typeof key === "string" && key.startsWith(`/api/links/_count`),+ undefined,+ { revalidate: true },+ );+ }, 500);+ setTimeout(() => {+ setPollLinks(false);+ clearInterval(pollingInterval);+ }, 30000);+ }+ }, [pollLinks]);+// handle invite and oauth modalsuseEffect(() => {if (error && (error.status === 409 || error.status === 410)) {@@ -68,6 +96,7 @@ export default function ModalProvider({ children }: { children: ReactNode }) {setShowAddEditDomainModal,setShowAddEditLinkModal,setShowImportLinksModal,+ setPollLinks,}}><GoogleOauthModal />diff --git a/app/ui/tooltip.tsx b/app/ui/tooltip.tsxindex fcb3362210..a449067b49 100644--- a/app/ui/tooltip.tsx+++ b/app/ui/tooltip.tsx@@ -110,13 +110,12 @@ export default function Tooltip({</TooltipPrimitive.Trigger><TooltipPrimitive.Portal><TooltipPrimitive.Content- sideOffset={4}+ sideOffset={8}side="top"- className="z-50 hidden animate-slide-up-fade items-center overflow-hidden rounded-md border border-gray-200 bg-white drop-shadow-lg sm:block"+ className="z-50 hidden animate-slide-up-fade items-center overflow-hidden rounded-md border border-gray-100 bg-white shadow-md sm:block">- <TooltipPrimitive.Arrow className="fill-current text-white" />{typeof content === "string" ? (- <div className="p-4">+ <div className="px-4 py-2"><span className="block max-w-xs text-center text-sm text-gray-700">{content}</span>@@ -124,7 +123,6 @@ export default function Tooltip({) : (content)}- <TooltipPrimitive.Arrow className="fill-current text-white" /></TooltipPrimitive.Content></TooltipPrimitive.Portal></TooltipPrimitive.Root>diff --git a/components/app/links/link-filters.tsx b/components/app/links/link-filters.tsxindex e3b2ec6f70..a288450cba 100644--- a/components/app/links/link-filters.tsx+++ b/components/app/links/link-filters.tsx@@ -133,7 +133,7 @@ const SearchBox = ({ searchInputRef }) => {<div className="relative"><div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">{isValidating && searchInputRef.current?.value.length > 0 ? (- <LoadingSpinner />+ <LoadingSpinner className="h-4 w-4" />) : (<Search className="h-4 w-4 text-gray-400" />)}diff --git a/components/app/modals/import-links-modal.tsx b/components/app/modals/import-links-modal.tsxindex e5c9295fab..0d3bea75fe 100644--- a/components/app/modals/import-links-modal.tsx+++ b/components/app/modals/import-links-modal.tsx@@ -1,8 +1,9 @@-import { useRouter } from "next/router";+import { NextRouter, useRouter } from "next/router";import {Dispatch,SetStateAction,useCallback,+ useContext,useEffect,useMemo,useState,@@ -14,7 +15,12 @@ import Switch from "#/ui/switch";import Button from "#/ui/button";import { toast } from "sonner";import { ArrowRight } from "lucide-react";-import Link from "next/link";+import { 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";function ImportLinksModal({showImportLinksModal,@@ -23,46 +29,62 @@ function ImportLinksModal({showImportLinksModal: boolean;setShowImportLinksModal: Dispatch<SetStateAction<boolean>>;}) {+ const { id: projectId } = useProject();const router = useRouter();- const { slug } = router.query;- const { logo, exceededUsage } = useProject();+ const { slug, import: importSource } = router.query;- const [importing, setImporting] = useState(false);+ const [redirecting, setRedirecting] = useState(false);- const onKeyDown = useCallback(- (e: KeyboardEvent) => {- const target = e.target as HTMLElement;- const existingModalBackdrop = document.getElementById("modal-backdrop");- // only open modal with keyboard shortcut if:- // - project has not exceeded usage limit- // - c is pressed- // - user is not pressing cmd/ctrl + c- // - user is not typing in an input or textarea- // - there is no existing modal backdrop (i.e. no other modal is open)- if (- !exceededUsage &&- e.key === "i" &&- !e.metaKey &&- !e.ctrlKey &&- target.tagName !== "INPUT" &&- target.tagName !== "TEXTAREA" &&- !existingModalBackdrop- ) {- setShowImportLinksModal(true);- }+ const { data: groups, isLoading } = useSWR<BitlyGroupProps[]>(+ slug && `/api/projects/${slug}/import/bitly`,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ refreshInterval: 0,},- [exceededUsage],);+ const [selectedDomains, setSelectedDomains] = useState<+ {+ domain: string;+ bitlyGroup: string;+ }[]+ >([]);+ const [selectedGroupTags, setSelectedGroupTags] = useState<string[]>([]);++ const [importing, setImporting] = useState(false);+ const { setPollLinks } = useContext(ModalContext);+useEffect(() => {- document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [onKeyDown]);+ if (importSource) {+ setShowImportLinksModal(true);+ } else {+ setShowImportLinksModal(false);+ }+ }, [importSource]);++ const closeModal = (router: NextRouter) => {+ delete router.query.import;+ // here, we omit the slug from the query string as well+ const { slug, ...finalQuery } = router.query;+ router.push({+ pathname: `/${router.query.slug}`,+ query: finalQuery,+ });+ };++ const bitlyOAuthURL = `https://bitly.com/oauth/authorize?client_id=${process.env.NEXT_PUBLIC_BITLY_CLIENT_ID}&redirect_uri=${process.env.NEXT_PUBLIC_BITLY_REDIRECT_URI}&state=${projectId}`;++ const isSelected = (domain: string) => {+ return selectedDomains.find((d) => d.domain === domain) ? true : false;+ };return (<ModalshowModal={showImportLinksModal}setShowModal={setShowImportLinksModal}+ onClose={() => closeModal(router)}><div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200"><div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-8 sm:px-16">@@ -85,77 +107,135 @@ function ImportLinksModal({</div><div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">- <Link- href={`https://bitly.com/oauth/authorize?client_id=${process.env.NEXT_PUBLIC_BITLY_CLIENT_ID}&redirect_uri=${process.env.NEXT_PUBLIC_BITLY_REDIRECT_URI}`}- className="flex h-10 w-full items-center justify-center space-x-2 rounded-md border border-gray-200 bg-white transition-all hover:border-black focus:outline-none"- >- <img- src="/_static/icons/bitly.svg"- alt="Bitly logo"- className="h-5 w-5 rounded-full border border-gray-200"- />- <p className="text-sm text-gray-500 hover:text-black">- Sign in with Bitly- </p>- </Link>- </div>- {/* <form- onSubmit={async (e) => {- e.preventDefault();- setImporting(true);- fetch(`/api/projects/${slug}/import/bitly`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(data),- }).then(async (res) => {- setImporting(false);-- if (res.status === 200) {- toast.success("Links imported successfully");- } else {- const error = await res.text();- toast.error(error);- }- });- }}- className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"- >- <div className="flex items-center justify-between bg-gray-50">- <p className="text-sm font-medium text-gray-900">Preserve Tags</p>- <Switch- fn={() =>- setData((prev) => ({ ...prev, preserveTags: !preserveTags }))+ {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>+ </button>+ ) : groups ? (+ <form+ onSubmit={async (e) => {+ e.preventDefault();+ setImporting(true);+ toast.promise(+ fetch(`/api/projects/${slug}/import/bitly`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ selectedDomains,+ selectedGroupTags,+ }),+ }).then(() => {+ setImporting(false);+ closeModal(router);+ mutate(`/api/projects/${slug}/domains`);+ setPollLinks(true);+ }),+ {+ loading: "Adding links to import queue...",+ success:+ "Successfully added links to import queue! You can now safely navigate from this tab – we will send you an email when your links have been fully imported.",+ error: "Error adding links to import queue",+ },+ );+ }}+ 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">+ <div className="flex items-center justify-between">+ <p className="text-sm font-medium text-gray-700">+ Domains+ </p>+ <Tooltip content="Your Bitly group ID">+ <p className="cursor-default text-xs uppercase text-gray-400 transition-colors hover:text-gray-700">+ {guid}+ </p>+ </Tooltip>+ </div>+ {bsds.map((bsd) => (+ <div 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>+ ))}+ <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>+ <Switch+ fn={() => {+ if (selectedGroupTags.includes(guid)) {+ setSelectedGroupTags((prev) =>+ prev.filter((g) => g !== guid),+ );+ } else {+ setSelectedGroupTags((prev) => [...prev, guid]);+ }+ }}+ checked={selectedGroupTags.includes(guid)}+ />+ </div>+ </div>+ ))}+ </div>+ <Button+ text="Confirm import"+ loading={importing}+ disabled={selectedDomains.length === 0}+ />+ <a+ href={bitlyOAuthURL}+ className="text-center text-xs text-gray-500 underline underline-offset-4 transition-colors hover:text-gray-800"+ >+ Sign in to a different Bitly account?+ </a>+ </form>+ ) : (+ <Button+ text="Sign in with Bitly"+ variant="secondary"+ loading={redirecting}+ icon={+ <img+ src="/_static/icons/bitly.svg"+ alt="Bitly logo"+ className="h-5 w-5 rounded-full border border-gray-200"+ />}- checked={preserveTags}+ onClick={() => {+ setRedirecting(true);+ router.push(bitlyOAuthURL);+ }}/>- </div>-- <div className="grid gap-2">- <Button text="Confirm import" loading={importing} />- </div>- </form> */}+ )}+ </div></div></Modal>);}-function ImportLinksButton({- setShowImportLinksModal,-}: {- setShowImportLinksModal: Dispatch<SetStateAction<boolean>>;-}) {- return (- <button- onClick={() => setShowImportLinksModal(true)}- className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"- >- Add Domain- </button>- );-}-export function useImportLinksModal() {const [showImportLinksModal, setShowImportLinksModal] = useState(false);@@ -168,22 +248,11 @@ export function useImportLinksModal() {);}, [showImportLinksModal, setShowImportLinksModal]);- const ImportLinksButtonCallback = useCallback(() => {- return (- <ImportLinksButton setShowImportLinksModal={setShowImportLinksModal} />- );- }, [setShowImportLinksModal]);-return useMemo(() => ({setShowImportLinksModal,ImportLinksModal: ImportLinksModalCallback,- ImportLinksButton: ImportLinksButtonCallback,}),- [- setShowImportLinksModal,- ImportLinksModalCallback,- ImportLinksButtonCallback,- ],+ [setShowImportLinksModal, ImportLinksModalCallback],);}diff --git a/components/layout/app/project-select.tsx b/components/layout/app/project-select.tsxindex 2119f08d1a..90f0c79fac 100644--- a/components/layout/app/project-select.tsx+++ b/components/layout/app/project-select.tsx@@ -65,7 +65,13 @@ export default function ProjectSelect() {return (<div><Popover- content={<ProjectList selected={selected} projects={projects} />}+ content={+ <ProjectList+ selected={selected}+ projects={projects}+ setOpenPopover={setOpenPopover}+ />+ }openPopover={openPopover}setOpenPopover={setOpenPopover}>@@ -102,6 +108,7 @@ export default function ProjectSelect() {function ProjectList({selected,projects,+ setOpenPopover,}: {selected: {name: string;@@ -110,6 +117,7 @@ function ProjectList({plan: PlanProps;};projects: ProjectWithDomainProps[];+ setOpenPopover: (open: boolean) => void;}) {const { data: session } = useSession();const { setShowAddProjectModal } = useContext(ModalContext);@@ -181,7 +189,10 @@ function ProjectList({))}<buttonkey="add"- onClick={() => setShowAddProjectModal(true)}+ onClick={() => {+ setOpenPopover(false);+ setShowAddProjectModal(true);+ }}className="flex w-full cursor-pointer items-center space-x-2 rounded-md p-2 transition-all duration-75 hover:bg-gray-100"><PlusCircle className="h-7 w-7 text-gray-600" />diff --git a/components/shared/modal.tsx b/components/shared/modal.tsxindex bfd2bf2d6e..ec86f9b96b 100644--- a/components/shared/modal.tsx+++ b/components/shared/modal.tsx@@ -15,6 +15,7 @@ export default function Modal({setShowModal,bgColor = "bg-white",closeWithX,+ onClose,hideBackdrop,mobileOnly,}: {@@ -23,6 +24,7 @@ export default function Modal({setShowModal: Dispatch<SetStateAction<boolean>>;bgColor?: string;closeWithX?: boolean;+ onClose?: () => void;hideBackdrop?: boolean;mobileOnly?: boolean;}) {@@ -35,9 +37,10 @@ export default function Modal({(closeWithX?: boolean) => {if (closeWithX) {return;- } else {- setShowModal(false);+ } else if (onClose) {+ onClose();}+ setShowModal(false);},[key, router, setShowModal],);diff --git a/lib/cron/import.tsx b/lib/cron/import.tsxindex 922edd6ab1..95c11d2f69 100644--- a/lib/cron/import.tsx+++ b/lib/cron/import.tsx@@ -1,15 +1,15 @@import prisma from "#/lib/prisma";import { redis } from "#/lib/upstash";import { randomBadgeColor } from "@/components/app/links/tag-badge";+import { sendEmail } from "emails";// recursive function to check if pagination.searchAfter is not an empty string, else break// rate limit for /groups/{group_guid}/bitlinks is 1500 per hour or 150 per minuteexport const importLinksFromBitly = async ({projectId,- projectDomains,bitlyGroup,+ domains,bitlyApiKey,- preserveTags,searchAfter = null,count = 0,}) => {@@ -27,27 +27,24 @@ export const importLinksFromBitly = async ({const { links, pagination } = data;const nextSearchAfter = pagination.search_after;- const pipeline = redis.pipeline();+ // const pipeline = redis.pipeline();// convert links to format that can be imported into databaseconst importedLinks = links.map((link) => {- const { id, long_url: url, title, archived, tags } = link;+ const { id, long_url: url, title, archived, created_at } = link;const [domain, key] = id.split("/");// if domain is not in project domains, skip (could be a bit.ly link or old short domain)- if (!projectDomains.includes(domain)) {+ if (!domains.includes(domain)) {return null;}- pipeline.set(- `${domain}:${key}`,- {- url: encodeURIComponent(url),- },- {- nx: true,- },- );- const tag = tags[0];+ // pipeline.set(+ // `${domain}:${key}`,+ // {+ // url: encodeURIComponent(url),+ // },+ // );+ const createdAt = new Date(created_at).toISOString();return {projectId,domain,@@ -55,36 +52,19 @@ export const importLinksFromBitly = async ({url,title,archived,- // if we're preserving tags, connect or create the first tag- ...(preserveTags && {- tag: {- connectOrCreate: {- where: {- name_projectId: {- name: tag,- projectId,- },- },- create: {- name: tag,- color: randomBadgeColor(),- projectId,- },- },- },- }),+ createdAt,};}).filter((link) => link !== null);// import links into database- // await Promise.all([- // prisma.link.createMany({- // data: importedLinks,- // skipDuplicates: true,- // }),- // pipeline.exec(),- // ]);+ await Promise.all([+ prisma.link.createMany({+ data: importedLinks,+ skipDuplicates: true,+ }),+ // pipeline.exec(),+ ]);count += importedLinks.length;@@ -98,14 +78,22 @@ export const importLinksFromBitly = async ({await new Promise((resolve) => setTimeout(resolve, 500));if (nextSearchAfter === "") {+ await Promise.all([+ // delete key from redis+ redis.del(`import:bitly:${projectId}`),+ // send email to user+ // sendEmail({+ // subject: `Your Bitly links have been imported!`,+ // email: user+ // })+ ]);return count;} else {return await importLinksFromBitly({projectId,- projectDomains,+ domains,bitlyGroup,bitlyApiKey,- preserveTags,searchAfter: nextSearchAfter,count,});diff --git a/lib/types.ts b/lib/types.tsindex c7d44c9eed..88f58d546f 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -101,3 +101,9 @@ export interface DomainProps {target?: string;type: "redirect" | "rewrite";}++export interface BitlyGroupProps {+ guid: string;+ bsds: string[]; // custom domains+ tags: string[];+}diff --git a/lib/utils.ts b/lib/utils.tsindex c05befde6c..a4e6f641f5 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -413,6 +413,7 @@ export const log = async ({type: "cron" | "links";mention?: boolean;}) => {+ if (process.env.NODE_ENV === "development") console.log(message);/* Log a message to the console */const HOOK = logTypeToEnv[type];if (!HOOK) return;diff --git a/pages/_app.tsx b/pages/_app.tsxindex 45dcb1b464..3577dc51d8 100644--- a/pages/_app.tsx+++ b/pages/_app.tsx@@ -14,7 +14,7 @@ function MyApp({}: AppProps<{ session: Session }>) {return (<SessionProvider session={session}>- <Toaster />+ <Toaster closeButton /><ModalProvider><main className={cn(satoshi.variable, inter.variable)}><Component {...pageProps} />diff --git a/pages/api/cron/import.ts b/pages/api/cron/import.tsdeleted file mode 100644index bfe14424f3..0000000000--- a/pages/api/cron/import.ts+++ /dev/null@@ -1,48 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";-import { verifySignature } from "@upstash/qstash/nextjs";-import { log } from "#/lib/utils";-import { importLinksFromBitly } from "#/lib/cron/import";--/**- * Cron to update the usage stats of each project.- * Runs once every day at 7AM PST.- **/--async function handler(req: NextApiRequest, res: NextApiResponse) {- try {- let results;- const { provider, emailToNotify } = req.body;- if (provider === "bitly") {- results = await importLinksFromBitly(req.body);- }- res.status(200).json(results);- } catch (error) {- await log({- message: "Import cron failed. Error: " + error.message,- type: "cron",- mention: true,- });- res.status(500).json({ error: error.message });- }-}--/**- * verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.-- * This will only run in production. In development, it will return the handler without verifying the signature.- */-const Cron = () => {- if (process.env.NODE_ENV === "development") {- return handler;- } else {- return verifySignature(handler);- }-};--export default Cron();--export const config = {- api: {- bodyParser: false,- },-};diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.tsindex 4bc20248ad..21b6df6fc9 100644--- a/pages/api/projects/[slug]/domains/index.ts+++ b/pages/api/projects/[slug]/domains/index.ts@@ -23,7 +23,6 @@ export default withProjectAuth(async (req, res, project) => {// POST /api/projects/[slug]/domains - add a domain} else if (req.method === "POST") {const { slug: domain, primary, target, type } = req.body;-const validDomain = await validateDomain(domain, project.id);if (validDomain !== true) {return res.status(422).json({diff --git a/pages/api/projects/[slug]/import/bitly.ts b/pages/api/projects/[slug]/import/bitly.tsindex 3082bf98cc..895c93aea9 100644--- a/pages/api/projects/[slug]/import/bitly.ts+++ b/pages/api/projects/[slug]/import/bitly.ts@@ -1,67 +1,112 @@+import { addDomainToVercel } from "#/lib/api/domains";import { withProjectAuth } from "#/lib/auth";import prisma from "#/lib/prisma";-import { qstash } from "#/lib/upstash";+import { BitlyGroupProps } from "#/lib/types";+import { qstash, redis } from "#/lib/upstash";export default withProjectAuth(async (req, res, project, session) => {- const { bitlyGroup, bitlyApiKey, preserveTags } = req.body;+ // get bitly groups and their respective domains+ if (req.method === "GET") {+ const accessToken = await redis.get(`import:bitly:${project.id}`);+ if (!accessToken) {+ return res.status(200).end("No Bitly access token found");+ }- const [bitlyGroupDomains, projectDomains] = await Promise.all([- fetch(`https://api-ssl.bitly.com/v4/groups/${bitlyGroup}`, {+ const response = await fetch(`https://api-ssl.bitly.com/v4/groups`, {headers: {"Content-Type": "application/json",- Authorization: `Bearer ${bitlyApiKey}`,+ Authorization: `Bearer ${accessToken}`,},- }).then(async (r) => {- const data = await r.json();- if (data.message === "FORBIDDEN") {- return null;- }- return data.bsds as string[];- }),- prisma.domain- .findMany({- where: {- projectId: project.id,- },- select: {- slug: true,- },- })- .then((domains) => domains.map((domain) => domain.slug)),- ]);+ });+ const data = await response.json();+ if (data.message === "FORBIDDEN") {+ return res.status(403).end("Invalid Bitly access token");+ }- if (!bitlyGroupDomains) {- return res.status(400).end("Invalid Bitly API key for given Bitly group");- }+ const groups = data.groups+ // filter for active groups only+ .filter(({ is_active }) => is_active) as BitlyGroupProps[];++ const groupsWithTags = await Promise.all(+ groups.map(async (group) => ({+ ...group,+ tags: await fetch(+ `https://api-ssl.bitly.com/v4/groups/${group.guid}/tags`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${accessToken}`,+ },+ },+ )+ .then((r) => r.json())+ .then((r) => r.tags),+ })),+ );++ return res.status(200).json(groupsWithTags);++ // create job to import links from bitly+ } else if (req.method === "POST") {+ const { selectedDomains, selectedGroupTags } = req.body;- const missingDomains = bitlyGroupDomains.filter(- (domain) => !projectDomains.includes(domain),- );+ // 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(({ slug }) => addDomainToVercel(slug)),+ ]);+ }- if (missingDomains.length > 0) {- return res- .status(400)- .end(- `All domains in your Bitly group must be added to your project before importing. The following domains are missing from your project: "${missingDomains.join(- ", ",- )}"`,+ // convert data to array of groups with their respective domains+ const groups = selectedDomains.reduce((result, { domain, bitlyGroup }) => {+ const existingGroup = result.find(+ (item) => item.bitlyGroup === bitlyGroup,);- }+ if (existingGroup) {+ existingGroup.domains.push(domain);+ } else {+ result.push({+ bitlyGroup,+ domains: [domain],+ keepTags: selectedGroupTags.includes(bitlyGroup),+ });+ }+ return result;+ }, []);- // const response = await qstash.publishJSON({- // url: "https://dub.sh/api/cron/import",- // body: {- // provider: "bitly",- // providerOpts: {- // bitlyGroup,- // bitlyApiKey,- // preserveTags,- // },- // projectId: project.id,- // projectDomains,- // emailToNotify: session.user.email,- // },- // });+ // const response = await Promise.all(+ // groups+ // // only add groups that have at least 1 domain selected for import+ // .filter(({ domains }) => domains.length > 0)+ // .map(({ bitlyGroup, domains }) =>+ // qstash.publishJSON({+ // url: "https://067b-2600-1700-b5e4-b50-8197-b987-5375-e928.ngrok-free.app/api/cron/import",+ // body: {+ // provider: "bitly",+ // projectId: project.id,+ // bitlyGroup,+ // domains,+ // },+ // }),+ // ),+ // );- return res.status(200).json({ response: "ok" });+ console.log(groups);++ return res.status(200).json(groups);+ }});diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsxindex c8a7f3ef0d..feee848957 100644--- a/pages/app/[slug]/index.tsx+++ b/pages/app/[slug]/index.tsx@@ -9,9 +9,10 @@ import useDomains from "#/lib/swr/use-domains";import Popover from "@/components/shared/popover";import IconMenu from "@/components/shared/icon-menu";import { ChevronDown, FilePlus2, Import } from "lucide-react";-import { ModalContext } from "#/ui/modal-provider";+import { useRouter } from "next/router";export default function ProjectLinks() {+ const router = useRouter();const { slug, error, loading: loadingProject } = useProject();const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal();@@ -21,14 +22,19 @@ export default function ProjectLinks() {const { verified, loading: loadingDomains } = useDomains();- useEffect(() => {- if (!verified && !loadingProject && !loadingDomains && !error) {- setShowCompleteSetupModal(true);- }- }, [verified, loadingProject, loadingDomains, error]);+ // useEffect(() => {+ // if (+ // !verified &&+ // !loadingProject &&+ // !loadingDomains &&+ // !error &&+ // !document.getElementById("modal-backdrop")+ // ) {+ // setShowCompleteSetupModal(true);+ // }+ // }, [verified, loadingProject, loadingDomains, error]);const [openPopover, setOpenPopover] = useState(false);- const { setShowImportLinksModal } = useContext(ModalContext);return (<AppLayout>@@ -55,7 +61,12 @@ export default function ProjectLinks() {<buttononClick={() => {setOpenPopover(false);- setShowImportLinksModal(true);+ 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">diff --git a/yarn.lock b/yarn.lockindex 723bcea7b0..524485d44f 100644--- a/yarn.lock+++ b/yarn.lock@@ -7315,13 +7315,20 @@ react-use-measure@^2.0.4:dependencies:debounce "^1.2.1"[email protected], react@^18.2.0:version "18.2.0"resolved "https://registry.npmjs.org/react/-/react-18.2.0.tgz"integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==dependencies:loose-envify "^1.1.0"+react@^18.2.0:+ version "18.2.0"+ resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5"+ integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==+ dependencies:+ loose-envify "^1.1.0"+read-cache@^1.0.0:version "1.0.0"resolved "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz"