41 Commits

Author SHA1 Message Date
36d1306180 remove test build 2023-06-24 02:13:05 +02:00
69bde313b5 test with latest
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:10:26 +02:00
7af3d87048 use new var in build
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:09:03 +02:00
73741230b1 adjust env method
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 7s
2023-06-24 02:08:26 +02:00
4f6d4f646a adjust echo script
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:07:19 +02:00
6169649261 add new step
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:06:10 +02:00
0560c4620c adjust awk script
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:05:01 +02:00
be3ee5e493 echo version
All checks were successful
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Successful in 6s
2023-06-24 02:02:42 +02:00
251e6ae3d6 add test build script
Some checks failed
Build a docker image for node-jellyfin-role-bot / build-docker-image (push) Failing after 9s
2023-06-24 02:00:56 +02:00
2edd0312dc Merge branch 'master' into feat/cicd 2023-06-24 02:00:28 +02:00
f2b5ee502f remove unnecessary scripts
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 10s
2023-06-14 22:35:59 +02:00
749e1c89ab clean up ci yaml 2023-06-14 22:35:51 +02:00
0d5799796a go back to normal docker commands
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 15s
2023-06-14 22:33:15 +02:00
b7986d276b fix env access
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 24s
2023-06-14 22:31:34 +02:00
8540381834 use bash explicitly
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 8s
2023-06-14 22:29:55 +02:00
7e67d1fed9 adjust scripts
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 8s
2023-06-14 22:28:29 +02:00
0cb19ba8f1 use bash scripts for docker stage
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 11s
2023-06-14 22:27:18 +02:00
5dcf766593 dockerbuild and dockerpush scripts 2023-06-14 22:27:05 +02:00
808bdd033e string it
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 9s
2023-06-14 22:20:06 +02:00
33f031d333 simplify push
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 9s
2023-06-14 22:14:46 +02:00
40d9523e21 doing it manually 2023-06-14 22:14:19 +02:00
26e74a62c1 add branch 2023-06-14 21:54:22 +02:00
c0f91aad79 add secrets to 'on' 2023-06-14 21:42:16 +02:00
79ffde5f34 check env step
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 23s
2023-06-14 21:30:23 +02:00
911b9e4884 adjust pipeline to be personalized
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 17s
2023-06-14 21:27:16 +02:00
31a9e0eb28 adjust url
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 22s
2023-06-14 19:44:50 +02:00
bcf788293e hardcoded docker tags
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 28s
2023-06-14 19:27:28 +02:00
934b6dfead remove custom script
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 15s
2023-06-14 19:21:22 +02:00
cd0c8c0017 latest tag by default
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 15s
2023-06-14 19:18:46 +02:00
83f803d0e7 remove metadata action
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 20s
2023-06-14 19:16:23 +02:00
2cb652aee6 add metadata and registry push
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 9s
2023-06-14 19:11:05 +02:00
034d14eb15 use a container with docker
All checks were successful
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Successful in 2m3s
2023-06-14 18:59:07 +02:00
c8bfc47ddf add docker login
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 14s
2023-06-13 23:47:22 +02:00
b67982ed38 ls
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 9s
2023-06-13 23:29:29 +02:00
e3144fc402 add checkout option 2023-06-13 23:29:03 +02:00
1970f4b0cb adjust docker build stage
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 34s
2023-06-13 23:24:56 +02:00
8ac4f568a0 add on push
Some checks failed
Build a docker image for node-jellyfin-role-ot / build-docker-image (push) Failing after 41s
2023-06-13 21:51:26 +02:00
09f4efc96c change os 2023-06-13 21:50:21 +02:00
6e0c3b8ef6 add gitea cicd 2023-06-13 21:49:04 +02:00
8ee36f7510 add woodpecker integration 2023-06-13 20:31:33 +02:00
1593e126eb add docker build files 2023-06-13 20:31:19 +02:00
34 changed files with 13626 additions and 13744 deletions

View File

@ -1,7 +0,0 @@
root = true
[*]
indent_style = tab
tab_width = 4
[*.ts]
indent_style = tab
tab_width = 4

View File

@ -14,4 +14,4 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v3
- name: Build Container
run: docker build --target compile .
run: docker build .

View File

@ -11,6 +11,7 @@ env:
jobs:
build-docker-image:
runs-on: ubuntu-latest
#if: gitea.ref == 'refs/heads/master'
container: catthehacker/ubuntu:act-latest
permissions:
contents: read
@ -21,8 +22,6 @@ jobs:
- name: Log in to the Container registry
run: docker login -u ${{ env.USER }} -p ${{ secrets.TOKEN }} ${{ env.REGISTRY }}
- name: Build Container
run: docker build --target compile -t "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" -t "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.VERSION }}" .
env:
version: $(cat package.json | awk 'match($0, /version/) {print $2}' | sed 's/[\",]//g') # extracts the version number from the package.json with bash magic
run: docker build -t "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" .
- name: Push Container
run: docker push --all-tags "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"

View File

@ -1,18 +0,0 @@
name: Run unit tests
on: [pull_request]
env:
REGISTRY: gitea.brudi.xyz
IMAGE_NAME: ${{ gitea.repository }}
USER: ${{ gitea.actor }}
jobs:
test:
runs-on: ubuntu-latest
container: catthehacker/ubuntu:act-latest
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Run Tests
run: docker build --target test .

View File

@ -1,22 +1,11 @@
FROM node:alpine as files
ENV TZ="Europe/Berlin"
WORKDIR /app
COPY [ "package-lock.json", "package.json", "index.ts", "tsconfig.json", "./" ]
FROM files as proddependencies
FROM node:alpine as Build
ENV NODE_ENV=production
WORKDIR /app
COPY [ "package-lock.json", "package.json", "index.ts", "tsconfig.json", "./" ]
COPY server ./server
RUN npm ci --omit=dev
FROM proddependencies as compile
COPY server ./server
RUN npm run build
CMD ["npm","run","start"]
FROM files as dependencies
RUN npm ci
FROM dependencies as test
COPY server ./server
COPY jest.config.js .
COPY tests ./tests
RUN npm run test

View File

@ -5,8 +5,8 @@ import { JellyfinHandler } from "./server/jellyfin/handler"
import { attachedImages } from "./server/assets/attachments"
const requestId = 'startup'
export const jellyfinHandler = new JellyfinHandler({ jellyfinToken: config.bot.workaround_token, jellyfinUrl: config.bot.jellyfin_url, movieCollectionId: config.bot.jf_collection_id, collectionUser: config.bot.jf_user })
export const yavinJellyfinHandler = new JellyfinHandler({ jellyfinToken: config.bot.yavin_jellyfin_token, jellyfinUrl: config.bot.yavin_jellyfin_url, movieCollectionId: config.bot.yavin_collection_id, collectionUser: config.bot.yavin_jellyfin_collection_user })
export const jellyfinHandler = new JellyfinHandler({jellyfinToken: config.bot.workaround_token, jellyfinUrl: config.bot.jellyfin_url, movieCollectionId: config.bot.jf_collection_id, collectionUser: config.bot.jf_user})
export const yavinJellyfinHandler = new JellyfinHandler({jellyfinToken: config.bot.yavin_jellyfin_token, jellyfinUrl: config.bot.yavin_jellyfin_url, movieCollectionId: config.bot.yavin_collection_id, collectionUser: config.bot.yavin_jellyfin_collection_user})
export const client = new ExtendedClient(jellyfinHandler)

View File

@ -1,19 +0,0 @@
module.exports = {
'roots': [
'<rootDir>/tests',
'<rootDir>/server'
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'testRegex': '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
'setupFiles': ["<rootDir>/tests/testenv.js"],
'moduleFileExtensions': [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
};

27
package-lock.json generated
View File

@ -30,13 +30,12 @@
"winston": "^3.8.2"
},
"devDependencies": {
"@types/jest": "^29.5.2",
"@types/jest": "^29.5.0",
"@typescript-eslint/eslint-plugin": "^5.58.0",
"@typescript-eslint/parser": "^5.58.0",
"eslint": "^8.38.0",
"jest": "^29.5.0",
"jest-cli": "^29.5.0",
"mockdate": "^3.0.5",
"nodemon": "^2.0.22",
"rimraf": "^5.0.0",
"ts-jest": "^29.1.0"
@ -1569,9 +1568,9 @@
}
},
"node_modules/@types/jest": {
"version": "29.5.2",
"resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.2.tgz",
"integrity": "sha512-mSoZVJF5YzGVCk+FsDxzDuH7s+SCkzrgKZzf0Z0T2WudhBUPoF6ktoTPC4R0ZoCPCV5xUvuU6ias5NvxcBcMMg==",
"version": "29.5.0",
"resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.0.tgz",
"integrity": "sha512-3Emr5VOl/aoBwnWcH/EFQvlSAmjV+XtV9GGu5mwdYew5vhQh0IUZx/60x0TzHDu09Bi7HMx10t/namdJw5QIcg==",
"dev": true,
"dependencies": {
"expect": "^29.0.0",
@ -4990,12 +4989,6 @@
"node": ">=10"
}
},
"node_modules/mockdate": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/mockdate/-/mockdate-3.0.5.tgz",
"integrity": "sha512-iniQP4rj1FhBdBYS/+eQv7j1tadJ9lJtdzgOpvsOHng/GbcDh2Fhdeq+ZRldrPYdXvCyfFUmFeEwEGXZB5I/AQ==",
"dev": true
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
@ -8146,9 +8139,9 @@
}
},
"@types/jest": {
"version": "29.5.2",
"resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.2.tgz",
"integrity": "sha512-mSoZVJF5YzGVCk+FsDxzDuH7s+SCkzrgKZzf0Z0T2WudhBUPoF6ktoTPC4R0ZoCPCV5xUvuU6ias5NvxcBcMMg==",
"version": "29.5.0",
"resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.0.tgz",
"integrity": "sha512-3Emr5VOl/aoBwnWcH/EFQvlSAmjV+XtV9GGu5mwdYew5vhQh0IUZx/60x0TzHDu09Bi7HMx10t/namdJw5QIcg==",
"dev": true,
"requires": {
"expect": "^29.0.0",
@ -10727,12 +10720,6 @@
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="
},
"mockdate": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/mockdate/-/mockdate-3.0.5.tgz",
"integrity": "sha512-iniQP4rj1FhBdBYS/+eQv7j1tadJ9lJtdzgOpvsOHng/GbcDh2Fhdeq+ZRldrPYdXvCyfFUmFeEwEGXZB5I/AQ==",
"dev": true
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",

View File

@ -33,18 +33,15 @@
"debuggable": "node build/index.js --inspect-brk",
"monitor": "nodemon build/index.js",
"lint": "eslint . --ext .ts",
"lint-fix": "eslint . --ext .ts --fix",
"test": "jest --runInBand",
"test-watch": "jest --watch"
"lint-fix": "eslint . --ext .ts --fix"
},
"devDependencies": {
"@types/jest": "^29.5.2",
"@types/jest": "^29.5.0",
"@typescript-eslint/eslint-plugin": "^5.58.0",
"@typescript-eslint/parser": "^5.58.0",
"eslint": "^8.38.0",
"jest": "^29.5.0",
"jest-cli": "^29.5.0",
"mockdate": "^3.0.5",
"nodemon": "^2.0.22",
"rimraf": "^5.0.0",
"ts-jest": "^29.1.0"

View File

@ -13,22 +13,22 @@ export default new Command({
options: [{
name: "typ",
type: ApplicationCommandOptionType.String,
description: "Was für ein announcement?",
choices: [{ name: "initial", value: "initial" }, { name: "votepls", value: "votepls" }, { name: "cancel", value: "cancel" }],
description:"Was für ein announcement?",
choices: [{name: "initial", value:"initial"},{name: "votepls", value:"votepls"},{name: "cancel", value:"cancel"}],
required: true
}],
run: async (interaction: RunOptions) => {
const command = interaction.interaction
const requestId = uuid()
if (!command.guildId) {
logger.error("COMMAND DOES NOT HAVE A GUILD ID; CANCELLING!!!", { requestId })
if(!command.guildId) {
logger.error("COMMAND DOES NOT HAVE A GUILD ID; CANCELLING!!!", {requestId})
return
}
const guildId = command.guildId
const announcementType = command.options.data.find(option => option.name.includes("typ"))
logger.info(`Got command for announcing ${announcementType?.value}!`, { guildId, requestId })
if (!announcementType) {
if(!announcementType) {
logger.error("Did not get an announcement type!", { guildId, requestId })
return
}
@ -40,7 +40,7 @@ export default new Command({
logger.info(`User ${command.member.displayName} seems to be admin`)
}
if ((<string>announcementType.value).includes("initial")) {
if((<string>announcementType.value).includes("initial")) {
sendInitialAnnouncement(guildId, requestId)
command.followUp("Ist rausgeschickt!")
} else {
@ -56,7 +56,7 @@ function isAdmin(member: GuildMember): boolean {
async function sendInitialAnnouncement(guildId: string, requestId: string): Promise<void> {
logger.info("Sending initial announcement")
const announcementChannel: Maybe<TextChannel> = client.getAnnouncementChannelForGuild(guildId)
if (!announcementChannel) {
if(!announcementChannel) {
logger.error("Could not find announcement channel. Aborting", { guildId, requestId })
return
}
@ -96,7 +96,7 @@ export async function manageAnnouncementRoles(guild: Guild, reaction: MessageRea
const allUsers = (await guild.members.fetch())
const usersWhoHaveRole: GuildMember[] = allUsers
.filter(member => member.roles.cache
.filter(member=> member.roles.cache
.find(role => role.id === config.bot.announcement_role) !== undefined)
.map(member => member)
@ -105,15 +105,15 @@ export async function manageAnnouncementRoles(guild: Guild, reaction: MessageRea
const usersWhoDontHaveRole: GuildMember[] = allUsers
.filter(member => member.roles.cache
.find(role => role.id === config.bot.announcement_role) === undefined)
.find(role=> role.id === config.bot.announcement_role) === undefined)
.map(member => member)
const usersWhoNeedRole: GuildMember[] = usersWhoDontHaveRole
.filter(userWhoNeeds => usersWhoWantRole.map(wanter => wanter.id).includes(userWhoNeeds.id))
logger.debug(`Theses users will get the role removed: ${JSON.stringify(usersWhoNeedRoleRevoked)}`, { guildId, requestId })
logger.debug(`Theses users will get the role added: ${JSON.stringify(usersWhoNeedRole)}`, { guildId, requestId })
logger.debug(`Theses users will get the role removed: ${JSON.stringify(usersWhoNeedRoleRevoked)}`, {guildId, requestId})
logger.debug(`Theses users will get the role added: ${JSON.stringify(usersWhoNeedRole)}`, {guildId, requestId})
usersWhoNeedRoleRevoked.forEach(user => user.roles.remove(announcementRole))
usersWhoNeedRole.forEach(user => user.roles.add(announcementRole))

View File

@ -20,7 +20,7 @@ export async function execute(event: GuildScheduledEvent) {
if (event.description.includes("!wp")) {
logger.info("Got manual create event of watchparty event!", { guildId, requestId })
if (event.description.includes("!private")) {
if(event.description.includes("!private")) {
logger.info("Event description contains \"!private\". Won't announce.", { guildId, requestId })
return
}

View File

@ -28,14 +28,14 @@ export async function execute(event: GuildScheduledEvent) {
logger.debug(`Movies: ${JSON.stringify(movies)}`, { guildId: event.guildId, requestId })
const announcementChannel: Maybe<TextChannel> = client.getAnnouncementChannelForGuild(event.guildId)
if (!announcementChannel) {
if(!announcementChannel) {
logger.error("Could not find announcement channel. Aborting", { guildId: event.guildId, requestId })
return
}
logger.debug(`Found channel ${JSON.stringify(announcementChannel, null, 2)}`, { guildId: event.guildId, requestId })
if (!event.scheduledStartAt) {
logger.info("EVENT DOES NOT HAVE STARTDATE; CANCELLING", { guildId: event.guildId, requestId })
if(!event.scheduledStartAt) {
logger.info("EVENT DOES NOT HAVE STARTDATE; CANCELLING", {guildId: event.guildId, requestId})
return
}
let message = `[Abstimmung] für https://discord.com/events/${event.guildId}/${event.id}\n<@&${config.bot.announcement_role}> Es gibt eine neue Abstimmung für die nächste Watchparty ${createDateStringFromEvent(event, event.guildId, requestId)}! Stimme hierunter für den nächsten Film ab!\n`
@ -46,7 +46,7 @@ export async function execute(event: GuildScheduledEvent) {
message = message.concat(NONE_OF_THAT).concat(": Wenn dir nichts davon gefällt.")
const options: MessageCreateOptions = {
allowedMentions: { parse: ["roles"] },
allowedMentions: { parse: ["roles"]},
content: message,
}

View File

@ -27,7 +27,7 @@ export async function execute(oldEvent: GuildScheduledEvent, newEvent: GuildSche
const wpAnnouncements = (await announcementChannel.messages.fetch()).filter(message => !message.cleanContent.includes("[initial]"))
const announcementsWithoutEvent = filterAnnouncementsByPendingWPs(wpAnnouncements, events)
logger.info(`Deleting ${announcementsWithoutEvent.length} announcements.`, { guildId, requestId })
logger.info(`Deleting ${announcementsWithoutEvent.length} announcements.`, {guildId, requestId})
announcementsWithoutEvent.forEach(message => message.delete())
}
} catch (error) {
@ -44,7 +44,7 @@ function filterAnnouncementsByPendingWPs(messages: Collection<string, Message<tr
foundEventForMessage = true
}
}
if (!foundEventForMessage) {
if(!foundEventForMessage){
filteredMessages.push(message)
}
}

View File

@ -12,7 +12,7 @@ export async function execute(oldState: VoiceState, newState: VoiceState) {
try {
logger.info(JSON.stringify(newState, null, 2))
//ignore events like mute/unmute
if (newState.channel?.id === oldState.channel?.id) {
if(newState.channel?.id === oldState.channel?.id) {
logger.info("Not handling VoiceState event because channelid of old and new was the same (i.e. mute/unmute event)")
return
}
@ -21,25 +21,25 @@ export async function execute(oldState: VoiceState, newState: VoiceState) {
.filter((key) => key.description?.toLowerCase().includes("!wp") && key.isActive())
.map((key) => key)
const scheduledEventUsers = (await Promise.all(scheduledEvents.map(event => event.fetchSubscribers({ withMember: true }))))
const scheduledEventUsers = (await Promise.all(scheduledEvents.map(event => event.fetchSubscribers({withMember: true}))))
//Dont handle users, that are already subscribed to the event. We only want to handle unsubscribed users here
let userFound = false;
scheduledEventUsers.forEach(collection => {
collection.each(key => {
logger.info(JSON.stringify(key, null, 2))
if (key.member.user.id === newState.member?.user.id)
if(key.member.user.id === newState.member?.user.id)
userFound = true;
})
})
if (userFound) {
if(userFound) {
logger.info(`Not handling VoiceState event because user was already subscribed and got an account from there. User: ${JSON.stringify(newState.member, null, 2)}`)
return
}
if (scheduledEvents.find(event => event.channelId === newState.channelId)) {
if (newState.member) {
if(newState.member){
logger.info("YO! Da ist jemand dem Channel mit dem Event beigetreten, ich kümmer mich mal um nen Account!")
const result = await jellyfinHandler.upsertUser(newState.member, "TEMPORARY", uuid())
if (result === UserUpsertResult.created) {
@ -53,7 +53,7 @@ export async function execute(oldState: VoiceState, newState: VoiceState) {
} else {
logger.info("VoiceState channelId was not the id of any channel with events")
}
} catch (error) {
}catch(error){
logger.error(error)
}
}

View File

@ -1,23 +1,23 @@
import { format, isToday, toDate } from "date-fns";
import { utcToZonedTime } from "date-fns-tz"
import {utcToZonedTime} from "date-fns-tz"
import { GuildScheduledEvent } from "discord.js";
import { logger } from "../logger";
import de from "date-fns/locale/de";
export function createDateStringFromEvent(event: GuildScheduledEvent, requestId: string, guildId?: string): string {
if (!event.scheduledStartAt) {
logger.error("Event has no start. Cannot create dateString.", { guildId, requestId })
if(!event.scheduledStartAt) {
logger.error("Event has no start. Cannot create dateString.", {guildId, requestId})
return `"habe keinen Startzeitpunkt ermitteln können"`
}
const timeZone = 'Europe/Berlin'
const zonedDateTime = utcToZonedTime(event.scheduledStartAt, timeZone)
const time = format(zonedDateTime, "HH:mm", { locale: de })
const time = format(zonedDateTime, "HH:mm", {locale: de})
if (isToday(zonedDateTime)) {
if(isToday(zonedDateTime)) {
return `heute um ${time}`
}
const date = format(zonedDateTime, "eeee dd.MM", { locale: de })
const date = format(zonedDateTime, "eeee dd.MM", {locale: de})
return `am ${date} um ${time}`
}

View File

@ -64,7 +64,7 @@ export class JellyfinHandler {
logger.debug(JSON.stringify(req), { requestId, guildId })
const createResult = await this.userApi.createUserByName(req)
if (createResult) {
if (createResult.policy) {
if(createResult.policy) {
this.setUserPermissions(createResult, requestId, guildId)
}
(await discordUser.createDM()).send(`Ich hab dir mal nen Account angelegt :)\nDein Username ist ${createResult.name}, dein Password ist "${req.createUserByNameRequest.password}"!`)
@ -74,8 +74,8 @@ export class JellyfinHandler {
}
public async setUserPermissions(user: UserDto, requestId: string, guildId?: string) {
if (!user.policy || !user.id) {
logger.error(`Cannot update user policy. User ${user.name} has no policy to modify`, { guildId, requestId })
if(!user.policy || !user.id) {
logger.error(`Cannot update user policy. User ${user.name} has no policy to modify`, {guildId, requestId})
return
}
user.policy.enableVideoPlaybackTranscoding = false
@ -273,7 +273,7 @@ export class JellyfinHandler {
let movieCount = 0
let movieNames: string[]
do {
movieNames = (await this.getRandomMovies(count, guildId, requestId)).filter(movie => movie.name && movie.name.length > 0).map(movie => <string>movie.name)
movieNames = (await this.getRandomMovies(count, guildId, requestId)).filter(movie => movie.name && movie.name.length > 0).map(movie => <string> movie.name)
movieCount = movieNames.length
} while (movieCount < count)
return movieNames

View File

@ -29,7 +29,7 @@ export interface ConfigurationParameters {
}
export class Configuration {
constructor(private configuration: ConfigurationParameters = {}) { }
constructor(private configuration: ConfigurationParameters = {}) {}
set config(configuration: Configuration) {
this.configuration = configuration;
@ -393,7 +393,7 @@ export interface ResponseTransformer<T> {
}
export class JSONApiResponse<T> {
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) { }
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) {}
async value(): Promise<T> {
return this.transformer(await this.raw.json());
@ -401,7 +401,7 @@ export class JSONApiResponse<T> {
}
export class VoidApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) {}
async value(): Promise<void> {
return undefined;
@ -409,7 +409,7 @@ export class VoidApiResponse {
}
export class BlobApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) {}
async value(): Promise<Blob> {
return await this.raw.blob();
@ -417,7 +417,7 @@ export class BlobApiResponse {
}
export class TextApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) {}
async value(): Promise<string> {
return await this.raw.text();

View File

@ -1,8 +1,5 @@
import { createLogger, format, transports } from "winston"
import { config } from "./configuration"
import { v4 } from "uuid"
export function newRequestId() { return v4() }
export const noGuildId = 'NoGuildId'
const printFn = format.printf(({ guildId, level, message, errorCode, requestId, timestamp: logTimestamp }: { [k: string]: string }) => {
@ -16,8 +13,7 @@ const logFormat = format.combine(
const consoleTransports = [
new transports.Console({
format: logFormat,
silent: process.env.NODE_ENV === 'testing'
format: logFormat
})
]
export const logger = createLogger({

View File

@ -130,7 +130,7 @@ export class ExtendedClient extends Client {
for (const guild of guilds.values()) {
logger.info("Starting background task for announcement role", { guildId: guild.id })
const textChannel: Maybe<TextChannel> = this.getAnnouncementChannelForGuild(guild.id)
if (!textChannel) {
if(!textChannel) {
logger.error("Could not find announcement channel. Aborting", { guildId: guild.id })
return
}
@ -174,7 +174,7 @@ export class ExtendedClient extends Client {
}
private async startPollCloseBackgroundTasks() {
for (const guild of this.guilds.cache) {
for(const guild of this.guilds.cache) {
this.pollCloseBackgroundTasks.set(guild[1].id, schedule("0 * * * * *", () => checkForPollsToClose(guild[1])))
}
}

View File

@ -1,16 +0,0 @@
import { GuildScheduledEvent } from "discord.js"
import { createDateStringFromEvent } from "../../server/helper/dateHelper"
import MockDate from 'mockdate'
beforeAll(() => {
MockDate.set('01-01-2023')
})
function getTestDate(date: string): GuildScheduledEvent {
return <GuildScheduledEvent>{ scheduledStartAt: new Date(date) }
}
test('createDateStringFromEvent - correct formatting', () => {
expect(createDateStringFromEvent(getTestDate('01-01-2023 12:30'), "")).toEqual('heute um 12:30')
expect(createDateStringFromEvent(getTestDate('01-02-2023 12:30'), "")).toEqual('am Montag 02.01 um 12:30')
expect(createDateStringFromEvent(getTestDate('01-03-2023 12:30'), "")).toEqual('am Dienstag 03.01 um 12:30')
})

View File

@ -1,28 +0,0 @@
import { Collection, GuildMember, Role } from "discord.js"
import { filterRolesFromMemberUpdate } from "../../server/helper/roleFilter"
function buildFakeRole(id: string, name: string): Role {
return <Role>{ id, name }
}
test('filterRolesFromMemberUpdate', () => {
const oldMemberRoles: Collection<string, Role> = new Collection<string, Role>()
oldMemberRoles.set('1', buildFakeRole('01', 'Role01'))
oldMemberRoles.set('2', buildFakeRole('02', 'Role02'))
const newMemberRoles: Collection<string, Role> = new Collection<string, Role>()
newMemberRoles.set('1', buildFakeRole('01', 'Role01'))
newMemberRoles.set('2', buildFakeRole('02', 'Role02'))
newMemberRoles.set('3', buildFakeRole('03', 'Role03'))
const oldMember: GuildMember = <GuildMember>{ roles: { cache: oldMemberRoles }, guild: { id: "guildid" } }
const newMember: GuildMember = <GuildMember>{ roles: { cache: newMemberRoles }, guild: { id: "guildid" } }
const output = filterRolesFromMemberUpdate(oldMember, newMember)
const expectedAddedRoles: Collection<string, Role> = new Collection<string, Role>()
expectedAddedRoles.set('3', buildFakeRole('03', 'Role03'))
const expectedRemovedRoles: Collection<string, Role> = new Collection<string, Role>()
expect(output.addedRoles).toEqual(expectedAddedRoles)
expect(output.removedRoles).toEqual(expectedRemovedRoles)
})

View File

@ -1,15 +0,0 @@
process.env.CLIENT_ID = "CLIENT_ID"
process.env.SECRET = "SECRET"
process.env.BOT_TOKEN = "BOT_TOKEN"
process.env.WATCHER_ROLE = "WATCHER_ROLE"
process.env.ADMIN_ROLE = "ADMIN_ROLE"
process.env.CHANNEL_ID = "CHANNEL_ID"
process.env.WATCHPARTY_ANNOUNCEMENT_ROLE = "WATCHPARTY_ANNOUNCEMENT_ROLE"
process.env.YAVIN_JELLYFIN_URL = "YAVIN_JELLYFIN_URL"
process.env.YAVIN_COLLECTION_ID = "YAVIN_COLLECTION_ID"
process.env.YAVIN_COLLECTION_USER = "YAVIN_COLLECTION_USER"
process.env.YAVIN_TOKEN = "YAVIN_TOKEN"
process.env.TOKEN = "TOKEN"
process.env.JELLYFIN_USER = "JELLYFIN_USER"
process.env.JELLYFIN_COLLECTION_ID = "JELLYFIN_COLLECTION_ID"
process.env.JELLYFIN_URL = "JELLYFIN_URL"

View File

@ -1,44 +1,61 @@
{
"extends": "@tsconfig/recommended/tsconfig.json",
"exclude": [
"node_modules"
],
"extends":"@tsconfig/recommended/tsconfig.json",
"exclude":["node_modules"],
"compilerOptions": {
/* Basic Options */
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"resolveJsonModule": true,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./build" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
"removeComments": true, /* Do not emit comments to output. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
//"noUncheckedIndexedAccess": true,
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
//"noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
"inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */