Compare commits

...

14 Commits

50 changed files with 1672 additions and 1518 deletions

View File

@@ -10,6 +10,12 @@ jobs:
name: Push frontend to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Wait
uses: NathanFirmo/wait-for-other-action@v1.0.4
with:
token: ${{ secrets.GITHUB_TOKEN }}
workflow: 'emojis.yml'
- name: Check out the repo
uses: actions/checkout@v3

37
apps/docs/.gitignore vendored
View File

@@ -1,28 +1,21 @@
# deps
/node_modules
# build output
dist/
# generated types
.astro/
# generated content
.contentlayer
.content-collections
.source
# dependencies
node_modules/
# test & build
/coverage
/.next/
/out/
/build
*.tsbuildinfo
# misc
.DS_Store
*.pem
/.pnp
.pnp.js
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# others
.env*.local
.vercel
next-env.d.ts
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store

4
apps/docs/.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}

11
apps/docs/.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}

View File

@@ -1,45 +1,49 @@
# docs
# Starlight Starter Kit: Basics
This is a Next.js application generated with
[Create Fumadocs](https://github.com/fuma-nama/fumadocs).
[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)
Run development server:
```bash
npm run dev
# or
pnpm dev
# or
yarn dev
```
yarn create astro@latest -- --template starlight
```
Open http://localhost:3000 with your browser to see the result.
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## Explore
## 🚀 Project Structure
In the project, you can see:
Inside of your Astro + Starlight project, you'll see the following folders and files:
- `lib/source.ts`: Code for content source adapter, [`loader()`](https://fumadocs.dev/docs/headless/source-api) provides the interface to access your content.
- `lib/layout.shared.tsx`: Shared options for layouts, optional but preferred to keep.
```
.
├── public/
├── src/
│ ├── assets/
│ ├── content/
│ │ └── docs/
│ └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json
```
| Route | Description |
| ------------------------- | ------------------------------------------------------ |
| `app/(home)` | The route group for your landing page and other pages. |
| `app/docs` | The documentation layout and pages. |
| `app/api/search/route.ts` | The Route Handler for search. |
Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.
### Fumadocs MDX
Images can be added to `src/assets/` and embedded in Markdown with a relative link.
A `source.config.ts` config file has been included, you can customise different options like frontmatter schema.
Static assets, like favicons, can be placed in the `public/` directory.
Read the [Introduction](https://fumadocs.dev/docs/mdx) for further details.
## 🧞 Commands
## Learn More
All commands are run from the root of the project, from a terminal:
To learn more about Next.js and Fumadocs, take a look at the following
resources:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `yarn install` | Installs dependencies |
| `yarn dev` | Starts local dev server at `localhost:4321` |
| `yarn build` | Build your production site to `./dist/` |
| `yarn preview` | Preview your build locally, before deploying |
| `yarn astro ...` | Run CLI commands like `astro add`, `astro check` |
| `yarn astro -- --help` | Get help using the Astro CLI |
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js
features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
- [Fumadocs](https://fumadocs.vercel.app) - learn about Fumadocs
## 👀 Want to learn more?
Check out [Starlights docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).

View File

@@ -0,0 +1,25 @@
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import mermaid from 'astro-mermaid';
import catppuccin from "@catppuccin/starlight";
// https://astro.build/config
export default defineConfig({
integrations: [
mermaid({
theme: 'base',
autoTheme: true
}),
starlight({
title: 'hctv docs',
social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/SrIzan10/hctv' }],
plugins: [
catppuccin({
dark: { flavor: "mocha", accent: "blue" },
light: { flavor: "latte", accent: "blue" }
}),
]
}),
],
});

View File

@@ -1,10 +0,0 @@
import { createMDX } from 'fumadocs-mdx/next';
const withMDX = createMDX();
/** @type {import('next').NextConfig} */
const config = {
reactStrictMode: true,
};
export default withMDX(config);

View File

@@ -1,31 +1,20 @@
{
"name": "@hctv/docs",
"version": "0.0.0",
"private": true,
"type": "module",
"version": "0.0.1",
"scripts": {
"build": "next build",
"dev": "next dev --turbo -p 3727",
"start": "next start",
"postinstall": "fumadocs-mdx"
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"fumadocs-core": "15.7.7",
"fumadocs-mdx": "11.8.2",
"fumadocs-ui": "15.7.7",
"@astrojs/starlight": "^0.35.2",
"@catppuccin/starlight": "^1.0.2",
"astro": "^5.6.1",
"astro-mermaid": "^1.0.4",
"mermaid": "^11.10.1",
"next": "15.5.2",
"next-themes": "^0.4.6",
"react": "^19.1.1",
"react-dom": "^19.1.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.12",
"@types/mdx": "^2.0.13",
"@types/node": "24.3.0",
"@types/react": "^19.1.12",
"@types/react-dom": "^19.1.9",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.12",
"typescript": "^5.9.2"
"sharp": "^0.34.2"
}
}

View File

@@ -1,5 +0,0 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
},
};

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><path fill-rule="evenodd" d="M81 36 64 0 47 36l-1 2-9-10a6 6 0 0 0-9 9l10 10h-2L0 64l36 17h2L28 91a6 6 0 1 0 9 9l9-10 1 2 17 36 17-36v-2l9 10a6 6 0 1 0 9-9l-9-9 2-1 36-17-36-17-2-1 9-9a6 6 0 1 0-9-9l-9 10v-2Zm-17 2-2 5c-4 8-11 15-19 19l-5 2 5 2c8 4 15 11 19 19l2 5 2-5c4-8 11-15 19-19l5-2-5-2c-8-4-15-11-19-19l-2-5Z" clip-rule="evenodd"/><path d="M118 19a6 6 0 0 0-9-9l-3 3a6 6 0 1 0 9 9l3-3Zm-96 4c-2 2-6 2-9 0l-3-3a6 6 0 1 1 9-9l3 3c3 2 3 6 0 9Zm0 82c-2-2-6-2-9 0l-3 3a6 6 0 1 0 9 9l3-3c3-2 3-6 0-9Zm96 4a6 6 0 0 1-9 9l-3-3a6 6 0 1 1 9-9l3 3Z"/><style>path{fill:#000}@media (prefers-color-scheme:dark){path{fill:#fff}}</style></svg>

After

Width:  |  Height:  |  Size: 696 B

View File

@@ -1,25 +0,0 @@
import {
defineConfig,
defineDocs,
frontmatterSchema,
metaSchema,
} from 'fumadocs-mdx/config';
import { remarkMdxMermaid } from 'fumadocs-core/mdx-plugins';
// You can customise Zod schemas for frontmatter and `meta.json` here
// see https://fumadocs.dev/docs/mdx/collections#define-docs
export const docs = defineDocs({
docs: {
schema: frontmatterSchema,
},
meta: {
schema: metaSchema,
},
});
export default defineConfig({
mdxOptions: {
// MDX options
remarkPlugins: [remarkMdxMermaid],
},
});

View File

@@ -1,8 +0,0 @@
export function GET() {
return new Response('Redirecting...', {
status: 302,
headers: {
Location: '/docs',
},
});
}

View File

@@ -1,7 +0,0 @@
import { source } from '@/lib/source';
import { createFromSource } from 'fumadocs-core/search/server';
export const { GET } = createFromSource(source, {
// https://docs.orama.com/docs/orama-js/supported-languages
language: 'english',
});

View File

@@ -1,52 +0,0 @@
import { source } from '@/lib/source';
import {
DocsBody,
DocsDescription,
DocsPage,
DocsTitle,
} from 'fumadocs-ui/page';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { createRelativeLink } from 'fumadocs-ui/mdx';
import { getMDXComponents } from '@/mdx-components';
export default async function Page(props: PageProps<'/docs/[[...slug]]'>) {
const params = await props.params;
const page = source.getPage(params.slug);
if (!page) notFound();
const MDXContent = page.data.body;
return (
<DocsPage toc={page.data.toc} full={page.data.full}>
<DocsTitle>{page.data.title}</DocsTitle>
<DocsDescription>{page.data.description}</DocsDescription>
<DocsBody>
<MDXContent
components={getMDXComponents({
// this allows you to link to other pages with relative file paths
// @ts-ignore
a: createRelativeLink(source, page),
})}
/>
</DocsBody>
</DocsPage>
);
}
export async function generateStaticParams() {
return source.generateParams();
}
export async function generateMetadata(
props: PageProps<'/docs/[[...slug]]'>,
): Promise<Metadata> {
const params = await props.params;
const page = source.getPage(params.slug);
if (!page) notFound();
return {
title: page.data.title,
description: page.data.description,
};
}

View File

@@ -1,11 +0,0 @@
import { DocsLayout } from 'fumadocs-ui/layouts/docs';
import { baseOptions } from '@/lib/layout.shared';
import { source } from '@/lib/source';
export default function Layout({ children }: LayoutProps<'/docs'>) {
return (
<DocsLayout tree={source.pageTree} {...baseOptions()}>
{children}
</DocsLayout>
);
}

View File

@@ -1,3 +0,0 @@
@import 'tailwindcss';
@import 'fumadocs-ui/css/neutral.css';
@import 'fumadocs-ui/css/preset.css';

View File

@@ -1,17 +0,0 @@
import '@/app/global.css';
import { RootProvider } from 'fumadocs-ui/provider';
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
});
export default function Layout({ children }: LayoutProps<'/'>) {
return (
<html lang="en" className={inter.className} suppressHydrationWarning>
<body className="flex flex-col min-h-screen">
<RootProvider>{children}</RootProvider>
</body>
</html>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View File

@@ -1,60 +0,0 @@
'use client';
import { use, useEffect, useId, useState } from 'react';
import { useTheme } from 'next-themes';
export function Mermaid({ chart }: { chart: string }) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) return;
return <MermaidContent chart={chart} />;
}
const cache = new Map<string, Promise<unknown>>();
function cachePromise<T>(
key: string,
setPromise: () => Promise<T>,
): Promise<T> {
const cached = cache.get(key);
if (cached) return cached as Promise<T>;
const promise = setPromise();
cache.set(key, promise);
return promise;
}
function MermaidContent({ chart }: { chart: string }) {
const id = useId();
const { resolvedTheme } = useTheme();
const { default: mermaid } = use(
cachePromise('mermaid', () => import('mermaid')),
);
mermaid.initialize({
startOnLoad: false,
securityLevel: 'loose',
fontFamily: 'inherit',
themeCSS: 'margin: 1.5rem auto 0;',
theme: resolvedTheme === 'dark' ? 'dark' : 'default',
});
const { svg, bindFunctions } = use(
cachePromise(`${chart}-${resolvedTheme}`, () => {
return mermaid.render(id, chart.replaceAll('\\n', '\n'));
}),
);
return (
<div
ref={(container) => {
if (container) bindFunctions?.(container);
}}
dangerouslySetInnerHTML={{ __html: svg }}
/>
);
}

View File

@@ -0,0 +1,7 @@
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};

View File

@@ -1,30 +0,0 @@
import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
/**
* Shared layout configurations
*
* you can customise layouts individually from:
* Home Layout: app/(home)/layout.tsx
* Docs Layout: app/docs/layout.tsx
*/
export function baseOptions(): BaseLayoutProps {
return {
nav: {
title: (
<>
<svg
width="24"
height="24"
xmlns="http://www.w3.org/2000/svg"
aria-label="Logo"
>
<circle cx={12} cy={12} r={12} fill="currentColor" />
</svg>
My App
</>
),
},
// see https://fumadocs.dev/docs/ui/navigation/links
links: [],
};
}

View File

@@ -1,9 +0,0 @@
import { docs } from '@/.source';
import { loader } from 'fumadocs-core/source';
// See https://fumadocs.vercel.app/docs/headless/source-api for more info
export const source = loader({
// it assigns a URL to your pages
baseUrl: '/docs',
source: docs.toFumadocsSource(),
});

View File

@@ -1,12 +0,0 @@
import defaultMdxComponents from 'fumadocs-ui/mdx';
import { Mermaid } from '@/components/mdx/mermaid';
import type { MDXComponents } from 'mdx/types';
// use this function to get MDX components, you will need it for rendering MDX
export function getMDXComponents(components?: MDXComponents): MDXComponents {
return {
...defaultMdxComponents,
Mermaid,
...components,
};
}

View File

@@ -1,45 +1,5 @@
{
"compilerOptions": {
"baseUrl": ".",
"target": "ESNext",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/.source": [
"./.source/index.ts"
],
"@/*": [
"./src/*"
]
},
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

0
apps/docs/yarn.lock Normal file
View File

View File

@@ -28,7 +28,11 @@ const nextConfig = {
},
{
hostname: 'emoji.slack-edge.com',
}
},
{
hostname: 'cdn.jsdelivr.net',
pathname: '/npm/emoji-datasource-twitter@15.1.2/img/twitter/64/*',
},
],
minimumCacheTTL: 120,
},

View File

@@ -64,7 +64,7 @@
"rehype-sanitize": "^6.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"sharp": "^0.34.2",
"sharp": "^0.34.3",
"sonner": "^1.4.41",
"swr": "^2.3.0",
"tailwind-merge": "^2.2.2",

View File

@@ -103,7 +103,7 @@ export async function POST(request: NextRequest) {
});
await queue.add(`newFollow:${username}`, {
text: `You started following \`${username}\`!\n_Stream notifications are enabled by default. If you want to disable them, you can do so in \`Profile > Notifications\`._`,
text: `You started following \`${username}\`!\n_Stream notifications are disabled by default. If you want to enable them, you can do so in \`Profile > Notifications\`._`,
channel: user.slack_id,
});
}

View File

@@ -61,6 +61,7 @@ interface ChannelSettingsClientProps {
streamKey: StreamKey | null;
followers: (Follow & { user: { id: string; slack_id: string } })[];
followerPersonalChannels: (Channel | null)[];
is247: boolean;
};
isOwner: boolean;
currentUser: User;
@@ -306,6 +307,27 @@ export default function ChannelSettingsClient({
</div>
),
},
{
name: 'is247',
value: channel.is247,
component: ({ field }) => (
<div className="flex items-center justify-between mt-2">
<div>
<label className="text-sm font-medium">24/7 Channel</label>
<p className="text-xs text-muted-foreground">
Mark this channel as always live. It will disable notifications on #hctv-streams.
</p>
</div>
<Switch
checked={field.value}
onCheckedChange={(checked) => {
field.onChange(checked);
}}
/>
<input type="hidden" {...field} value={field.value ? 'true' : 'false'} />
</div>
),
}
]}
schemaName="updateChannelSettings"
action={updateChannelSettings}

View File

@@ -10,15 +10,15 @@ import {
MediaSeekForwardButton,
MediaMuteButton,
MediaVolumeRange,
MediaFullscreenButton
MediaFullscreenButton,
} from 'media-chrome/react';
import HlsVideo from 'hls-video-element/react'
import HlsVideo from 'hls-video-element/react';
export default function StreamPlayer() {
const { username } = useParams();
return (
<MediaController className='w-full aspect-video'>
<MediaController className="w-full aspect-video">
<HlsVideo
src={`/api/rtmp/hls/${username}.m3u8`}
slot="media"
@@ -26,31 +26,35 @@ export default function StreamPlayer() {
autoplay
config={{
lowLatencyMode: true,
liveSyncDurationCount: 2,
liveMaxLatencyDurationCount: 4,
liveSyncDurationCount: 1,
liveMaxLatencyDurationCount: 2,
liveDurationInfinity: true,
enableWorker: true,
backBufferLength: 2,
startLevel: 0,
maxBufferLength: 4,
maxMaxBufferLength: 8,
backBufferLength: 1,
startLevel: -1,
maxBufferLength: 2,
maxMaxBufferLength: 4,
startFragPrefetch: true,
testBandwidth: false,
progressive: true,
maxBufferSize: 30 * 1000 * 1000,
maxBufferHole: 0.3,
highBufferWatchdogPeriod: 1,
nudgeOffset: 0.05,
nudgeMaxRetry: 2,
manifestLoadingTimeOut: 5000,
manifestLoadingMaxRetry: 2,
levelLoadingTimeOut: 5000,
fragLoadingTimeOut: 10000,
progressive: false,
maxBufferSize: 10 * 1000 * 1000,
maxBufferHole: 0.1,
highBufferWatchdogPeriod: 0.5,
nudgeOffset: 0.01,
nudgeMaxRetry: 3,
manifestLoadingTimeOut: 3000,
manifestLoadingMaxRetry: 3,
levelLoadingTimeOut: 3000,
fragLoadingTimeOut: 5000,
debug: process.env.NODE_ENV === 'development',
liveSyncDuration: 1,
liveMaxLatencyDuration: 3,
maxLiveSyncPlaybackRate: 1.5,
liveBackBufferLength: 0,
}}
/>
<MediaLoadingIndicator slot="centered-chrome" noAutohide />
<MediaControlBar className='w-full px-2'>
<MediaControlBar className="w-full px-2">
<div className="flex items-center gap-2">
<MediaPlayButton />
<MediaMuteButton />

View File

@@ -39,7 +39,7 @@ export function UniversalForm<T extends z.ZodType>({
otherSubmitButton,
submitButtonDivClassname,
}: UniversalFormProps<T>) {
// @ts-ignore idk why this error is happening, first apprearing on the react 19 update.
// @ts-expect-error - idk
const [state, formAction] = useActionState<{ success: boolean; error?: string }>(action, null);
const schema = schemaDb.find((s) => s.name === schemaName)?.zod;
@@ -56,9 +56,11 @@ export function UniversalForm<T extends z.ZodType>({
return { ...values, ...defaultValues };
}, [fields, defaultValues]);
const form = useForm<z.infer<T>>({
resolver: zodResolver(schema),
defaultValues: initialValues as z.infer<T>,
type FormData = z.infer<T>;
const form = useForm<FormData>({
resolver: zodResolver(schema as any),
defaultValues: initialValues as FormData,
});
React.useEffect(() => {
@@ -77,10 +79,10 @@ export function UniversalForm<T extends z.ZodType>({
<FormField
key={field.name}
control={form.control}
name={field.name as Path<z.infer<T>>}
name={field.name as Path<FormData>}
render={({ field: formField }) => (
<FormItem>
{field.type !== 'hidden' && <FormLabel>{field.label}</FormLabel>}
{(field.type !== 'hidden' || field.label) && <FormLabel>{field.label}</FormLabel>}
<FormControl>
{field.component ? (
field.component({ field: formField, ...field.componentProps })

View File

@@ -5,7 +5,7 @@ import { schemaDb } from './UniversalForm';
export type FormFieldConfig = {
name: string;
label: string;
label?: string;
type?: HTMLInputTypeAttribute;
placeholder?: string;
description?: string;

View File

@@ -202,6 +202,7 @@ export async function updateChannelSettings(prev: any, formData: FormData) {
data: {
description: zod.data.description || undefined,
pfpUrl: zod.data.pfpUrl,
is247: zod.data.is247,
},
});

View File

@@ -24,4 +24,5 @@ export const updateChannelSettingsSchema = z.object({
channelId: z.string().min(1),
pfpUrl: z.string(),
description: z.string().min(1).max(500),
is247: z.boolean(),
});

View File

@@ -102,6 +102,7 @@ export async function syncStream() {
if (stream.active) {
const existingStream = await prisma.streamInfo.findUnique({
where: { username: stream.name },
include: { channel: true },
});
if (existingStream && !existingStream.isLive) {
@@ -125,12 +126,14 @@ export async function syncStream() {
const queue = getNotificationQueue();
queue.add(`streamStartChannel:${existingStream.username}`, {
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hctv.srizan.dev/${existingStream.username}|Go check them out>`,
channel: process.env.NOTIFICATION_CHANNEL_ID!,
unfurl_links: true,
});
if (existingStream.enableNotifications) {
if (!existingStream.channel.is247) {
queue.add(`streamStartChannel:${existingStream.username}`, {
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hctv.srizan.dev/${existingStream.username}|Go check them out>`,
channel: process.env.NOTIFICATION_CHANNEL_ID!,
unfurl_links: true,
});
}
if (existingStream.enableNotifications && !existingStream.channel.is247) {
for (const follower of subscribedFollowers) {
queue.add(`streamStartDm:${follower.user.id}`, {
text: `${existingStream.username} is now *live*, streaming *${existingStream.title}* (${existingStream.category})!\n<https://hctv.srizan.dev/${existingStream.username}|Go check them out>\n_Stream notifications are enabled for this user. If you want to disable them, you can do so in \`Profile > Follows\`._`,

View File

@@ -28,8 +28,8 @@ rtmp {
hls on;
hls_type live;
hls_path /dev/shm/hls;
hls_fragment 2s;
hls_playlist_length 20s;
hls_fragment 1s;
hls_playlist_length 3s;
hls_cleanup on;
hls_fragment_naming timestamp;

View File

@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Channel" ADD COLUMN "is247" BOOLEAN NOT NULL DEFAULT false;

View File

@@ -52,6 +52,7 @@ model Channel {
followers Follow[] @relation("ChannelFollowers")
streamKey StreamKey?
obsChatGrantToken String @unique @default(cuid())
is247 Boolean @default(false)
@@index([ownerId])
}

View File

@@ -17,12 +17,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "backtrace"
version = "0.3.75"
@@ -186,12 +180,6 @@ version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-io"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
[[package]]
name = "futures-sink"
version = "0.3.31"
@@ -211,12 +199,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-io",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]]
@@ -501,16 +486,6 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956"
[[package]]
name = "lock_api"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.27"
@@ -625,29 +600,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "parking_lot"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets 0.52.6",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"
@@ -705,15 +657,6 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "redox_syscall"
version = "0.5.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6"
dependencies = [
"bitflags 2.9.1",
]
[[package]]
name = "reqwest"
version = "0.11.27"
@@ -803,12 +746,6 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "2.11.1"
@@ -882,15 +819,6 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "signal-hook-registry"
version = "1.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410"
dependencies = [
"libc",
]
[[package]]
name = "slab"
version = "0.4.10"
@@ -899,7 +827,7 @@ checksum = "04dc19736151f35336d325007ac991178d504a119863a2fcb3758cdb5e52c50d"
[[package]]
name = "slack-import-emojis"
version = "0.1.0"
version = "0.2.1"
dependencies = [
"reqwest",
"serde",
@@ -1012,9 +940,7 @@ dependencies = [
"io-uring",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"slab",
"socket2",
"tokio-macros",

View File

@@ -1,10 +1,10 @@
[package]
name = "slack-import-emojis"
version = "0.1.0"
version = "0.2.1"
edition = "2021"
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

View File

@@ -3,30 +3,53 @@ use serde::Deserialize;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::env;
#[derive(Debug, Deserialize)]
struct SlackEmojiResponse {
emoji: HashMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[allow(dead_code)]
error: Option<String>,
emoji: HashMap<String, String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[allow(dead_code)]
error: Option<String>,
}
#[derive(Debug, Deserialize)]
struct DefaultEmojiResponse {
emoji: HashMap<String, String>,
}
#[derive(Debug, Deserialize)]
struct EmojiData {
unified: String,
has_img_twitter: bool,
short_name: String,
}
#[tokio::main]
async fn main() {
let args: Vec<String> = env::args().collect();
if std::env::var("SLACK_TOKEN").is_err() {
eprintln!("Error: SLACK_TOKEN environment variable is not set.");
return;
}
let emojis = slack_request()
let mut slack_emojis = slack_request()
.await
.expect("Failed to fetch emojis from Slack API");
.expect("Failed to fetch slack_emojis from Slack API");
println!("{:?} slack_emojis fetched", slack_emojis.emoji.len());
if args.len() > 1 && args[1] == "default" {
let default_emojis = default_request()
.await
.expect("Failed to fetch default_emojis from GitHub");
println!("{:?} default_emojis fetched", default_emojis.emoji.len());
slack_emojis.emoji.extend(default_emojis.emoji);
}
println!("{:?} emojis fetched", emojis.emoji.len());
let mut file = File::create("emojis.json").expect("failed to create file for some reason");
let json_data = serde_json::to_string(&emojis.emoji).expect("failed to serialize emojis wtf");
file.write_all(json_data.as_bytes())
let json_data =
serde_json::to_string(&slack_emojis.emoji).expect("failed to serialize emojis wtf");
file
.write_all(json_data.as_bytes())
.expect("failed to write emojis to file");
println!("saved :yay:");
}
@@ -37,7 +60,10 @@ async fn slack_request() -> Result<SlackEmojiResponse, Box<dyn std::error::Error
.get("https://slack.com/api/emoji.list")
.header(
"Authorization",
format!("Bearer {}", std::env::var("SLACK_TOKEN").expect("SLACK_TOKEN not set")),
format!(
"Bearer {}",
std::env::var("SLACK_TOKEN").expect("SLACK_TOKEN not set")
),
)
.send()
.await;
@@ -50,3 +76,29 @@ async fn slack_request() -> Result<SlackEmojiResponse, Box<dyn std::error::Error
}
}
}
async fn default_request() -> Result<DefaultEmojiResponse, Box<dyn std::error::Error>> {
const CDN_URL: &str =
"https://cdn.jsdelivr.net/npm/emoji-datasource-twitter@15.1.2/img/twitter/64/";
let client = reqwest::Client::new();
let res = client
.get("https://raw.githubusercontent.com/iamcal/emoji-data/refs/heads/master/emoji.json")
.send()
.await;
match res {
Ok(response) => {
let emoji_data: Vec<EmojiData> = response.json().await?;
let emoji_map: HashMap<String, String> = emoji_data
.into_iter()
.filter(|e| e.has_img_twitter)
.map(|e| (e.short_name, format!("{}{}.png", CDN_URL, e.unified.to_lowercase())))
.collect();
Ok(DefaultEmojiResponse { emoji: emoji_map })
}
Err(err) => {
eprintln!("Error: {:?}", err);
Err(Box::new(err))
}
}
}

2431
yarn.lock

File diff suppressed because it is too large Load Diff