Compare commits
59 Commits
migration-
...
getbundles
| Author | SHA1 | Date | |
|---|---|---|---|
| 30168844f3 | |||
| 2e60e2e3d5 | |||
| 8254ec2093 | |||
| 7381d03045 | |||
| d7e865f84f | |||
| baa5a99855 | |||
| 68c2dacff4 | |||
| 55e0ce6d36 | |||
| 4ffad69c44 | |||
| f9438f2129 | |||
| 2247411ac8 | |||
| e61ecb1143 | |||
| e01421f17b | |||
| cc271021e0 | |||
| cc772504ae | |||
| 8dcb17a6a0 | |||
| a06896ffcc | |||
| 03f6623ed0 | |||
| 66f9d63b44 | |||
| a936df3144 | |||
| dc9dabca48 | |||
| 4680fd0875 | |||
| 323548c0ff | |||
| f4563c12c6 | |||
| 1b0cada848 | |||
| 750a74cd9f | |||
| 402ee4d81b | |||
| 1fa35ac0e3 | |||
| 680594e67c | |||
| 5593fcb4a0 | |||
| d7f3d3a7cf | |||
| 94cb95f4bf | |||
| c6651cdd91 | |||
| b35e2140b5 | |||
| f053dcb789 | |||
| aea7a24f76 | |||
| 8f0c2f4302 | |||
| 7dbe2b2701 | |||
| 5b9ef9fbbb | |||
| 4cdb11fcbd | |||
| 78f7c1b595 | |||
| bbd2906ebf | |||
| 1861c2eeed | |||
| f3965437b5 | |||
| 78e0e9f8ce | |||
| c926758db6 | |||
| b2b35aedc0 | |||
| f35e3ccbe0 | |||
| 7b0c0a7420 | |||
| c2bbbf311d | |||
| b8ca03220f | |||
| b87b0c875d | |||
| 11fbaf10db | |||
| 1229feb69c | |||
| 3efdc7c2e2 | |||
| 1fff931941 | |||
| f4e2db5a5f | |||
| 1d7561279b | |||
| 9e47ae0436 |
66
Dockerfile
66
Dockerfile
@@ -1,40 +1,62 @@
|
|||||||
FROM alpine:3.14
|
# Use a base image with Node.js 22.1.0
|
||||||
|
FROM node:22.1.0
|
||||||
|
|
||||||
|
# Set metadata for contact
|
||||||
LABEL maintainer="Rishi Ghan <rishi.ghan@gmail.com>"
|
LABEL maintainer="Rishi Ghan <rishi.ghan@gmail.com>"
|
||||||
|
|
||||||
# Show all node logs
|
# Set environment variables
|
||||||
ENV NPM_CONFIG_LOGLEVEL warn
|
ENV NPM_CONFIG_LOGLEVEL warn
|
||||||
ENV NODE_ENV=production
|
ENV NODE_ENV=production
|
||||||
|
|
||||||
|
# Set the working directory
|
||||||
WORKDIR /core-services
|
WORKDIR /core-services
|
||||||
|
|
||||||
|
# Install required packages
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
libvips-tools \
|
||||||
|
wget \
|
||||||
|
imagemagick \
|
||||||
|
python3 \
|
||||||
|
xvfb \
|
||||||
|
xz-utils \
|
||||||
|
curl \
|
||||||
|
bash \
|
||||||
|
software-properties-common
|
||||||
|
|
||||||
RUN apk add --update \
|
# Install p7zip
|
||||||
--repository http://nl.alpinelinux.org/alpine/v3.14/main \
|
RUN apt-get update && apt-get install -y p7zip
|
||||||
vips-tools \
|
|
||||||
wget \
|
|
||||||
imagemagick \
|
|
||||||
python3 \
|
|
||||||
unrar \
|
|
||||||
p7zip \
|
|
||||||
nodejs \
|
|
||||||
npm \
|
|
||||||
xvfb \
|
|
||||||
xz
|
|
||||||
|
|
||||||
|
# Install unrar directly from RARLAB
|
||||||
|
RUN wget https://www.rarlab.com/rar/rarlinux-x64-621.tar.gz \
|
||||||
|
&& tar -zxvf rarlinux-x64-621.tar.gz \
|
||||||
|
&& cp rar/unrar /usr/bin/ \
|
||||||
|
&& rm -rf rarlinux-x64-621.tar.gz rar
|
||||||
|
|
||||||
|
# Clean up package lists
|
||||||
|
RUN rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Verify Node.js installation
|
||||||
|
RUN node -v && npm -v
|
||||||
|
|
||||||
|
# Copy application configuration files
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
COPY moleculer.config.ts ./
|
COPY moleculer.config.ts ./
|
||||||
COPY tsconfig.json ./
|
COPY tsconfig.json ./
|
||||||
|
COPY scripts ./scripts
|
||||||
|
RUN chmod +x ./scripts/*
|
||||||
|
|
||||||
RUN npm i
|
# Install application dependencies
|
||||||
# Install Dependncies
|
RUN npm install
|
||||||
RUN npm install -g typescript ts-node
|
RUN npm install -g typescript ts-node
|
||||||
|
|
||||||
|
# Copy the rest of the application files
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Build and cleanup
|
# clean up
|
||||||
RUN npm run build \
|
RUN npm prune
|
||||||
&& npm prune
|
|
||||||
|
|
||||||
|
|
||||||
|
# Expose the application's port
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
# Start server
|
|
||||||
CMD ["npm", "start"]
|
# Command to run the application
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
|||||||
26
README.md
26
README.md
@@ -3,21 +3,35 @@
|
|||||||
This [moleculer-based](https://github.com/moleculerjs/moleculer-web) microservice houses endpoints for the following functions:
|
This [moleculer-based](https://github.com/moleculerjs/moleculer-web) microservice houses endpoints for the following functions:
|
||||||
|
|
||||||
1. Local import of a comic library into mongo (currently supports `cbr` and `cbz` files)
|
1. Local import of a comic library into mongo (currently supports `cbr` and `cbz` files)
|
||||||
2. Metadata extraction from file, `comicinfo.xml`
|
2. Metadata extraction from file, `comicinfo.xml`
|
||||||
3. Mongo comic object orchestration
|
3. Mongo comic object orchestration
|
||||||
4. CRUD operations on `Comic` model
|
4. CRUD operations on `Comic` model
|
||||||
5. Helper utils to help with image metadata extraction, file operations and more.
|
5. Helper utils to help with image metadata extraction, file operations and more.
|
||||||
|
|
||||||
## Local Development
|
## Local Development
|
||||||
|
|
||||||
1. ~~You need `calibre` in your local path.
|
1. You need the following dependencies installed: `mongo`, `elasticsearch` and `redis`
|
||||||
On `macOS` you can `brew install calibre` and make sure that `ebook-meta` is present on the path~~ Calibre is no longer required as a dependency. Ignore this step.
|
2. You also need binaries for `unrar` and `p7zip`
|
||||||
2. You need `mongo` for the data store. on `macOS` you can use [these instructions](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/) to install it
|
|
||||||
3. Clone this repo
|
3. Clone this repo
|
||||||
4. Run `npm i`
|
4. Run `npm i`
|
||||||
5. Assuming you installed mongo correctly, run `MONGO_URI=mongodb://localhost:27017/threetwo npm run dev` to start the service
|
5. Assuming you installed the dependencies correctly, run:
|
||||||
|
|
||||||
|
```
|
||||||
|
COMICS_DIRECTORY=<PATH_TO_COMICS_DIRECTORY> \
|
||||||
|
USERDATA_DIRECTORY=<PATH_TO_USERDATA_DIRECTORY> \
|
||||||
|
REDIS_URI=redis://<REDIS_HOST:REDIS_PORT> \
|
||||||
|
ELASTICSEARCH_URI=<ELASTICSEARCH_HOST:ELASTICSEARCH_PORT> \
|
||||||
|
MONGO_URI=mongodb://<MONGO_HOST:MONGO_PORT>/threetwo \
|
||||||
|
UNRAR_BIN_PATH=<UNRAR_BIN_PATH> \
|
||||||
|
SEVENZ_BINARY_PATH=<SEVENZ_BINARY_PATH> \
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
to start the service
|
||||||
|
|
||||||
6. You should see the service spin up and a list of all the endpoints in the terminal
|
6. You should see the service spin up and a list of all the endpoints in the terminal
|
||||||
7. The service can be accessed through `http://localhost:3000/api/import/*`
|
7. The service can be accessed through `http://localhost:3000/api/<serviceName>/*`
|
||||||
|
|
||||||
## Docker Instructions
|
## Docker Instructions
|
||||||
|
|
||||||
1. Build the image using `docker build . -t frishi/threetwo-import-service`. Give it a hot minute.
|
1. Build the image using `docker build . -t frishi/threetwo-import-service`. Give it a hot minute.
|
||||||
|
|||||||
@@ -1,10 +1,30 @@
|
|||||||
import { createClient } from "redis";
|
// Import the Redis library
|
||||||
const redisURL = new URL(process.env.REDIS_URI);
|
import IORedis from "ioredis";
|
||||||
|
|
||||||
const pubClient = createClient({ url: `redis://${redisURL.hostname}:6379` });
|
// Environment variable for Redis URI
|
||||||
(async () => {
|
const redisURI = process.env.REDIS_URI || "redis://localhost:6379";
|
||||||
await pubClient.connect();
|
console.log(`process.env.REDIS_URI is ${process.env.REDIS_URI}`);
|
||||||
})();
|
// Creating the publisher client
|
||||||
const subClient = pubClient.duplicate();
|
const pubClient = new IORedis(redisURI);
|
||||||
|
|
||||||
export { subClient, pubClient };
|
// Creating the subscriber client
|
||||||
|
const subClient = new IORedis(redisURI);
|
||||||
|
|
||||||
|
// Handle connection events for the publisher
|
||||||
|
pubClient.on("connect", () => {
|
||||||
|
console.log("Publisher client connected to Redis.");
|
||||||
|
});
|
||||||
|
pubClient.on("error", (err) => {
|
||||||
|
console.error("Publisher client failed to connect to Redis:", err);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Handle connection events for the subscriber
|
||||||
|
subClient.on("connect", () => {
|
||||||
|
console.log("Subscriber client connected to Redis.");
|
||||||
|
});
|
||||||
|
subClient.on("error", (err) => {
|
||||||
|
console.error("Subscriber client failed to connect to Redis:", err);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Export the clients for use in other parts of the application
|
||||||
|
export { pubClient, subClient };
|
||||||
|
|||||||
103
dependencies.docker-compose.yml
Normal file
103
dependencies.docker-compose.yml
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
services:
|
||||||
|
zoo1:
|
||||||
|
image: confluentinc/cp-zookeeper:7.3.2
|
||||||
|
hostname: zoo1
|
||||||
|
container_name: zoo1
|
||||||
|
ports:
|
||||||
|
- "2181:2181"
|
||||||
|
environment:
|
||||||
|
ZOOKEEPER_CLIENT_PORT: 2181
|
||||||
|
ZOOKEEPER_SERVER_ID: 1
|
||||||
|
ZOOKEEPER_SERVERS: zoo1:2888:3888
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
|
||||||
|
kafka1:
|
||||||
|
image: confluentinc/cp-kafka:7.3.2
|
||||||
|
hostname: kafka1
|
||||||
|
container_name: kafka1
|
||||||
|
ports:
|
||||||
|
- "9092:9092"
|
||||||
|
- "29092:29092"
|
||||||
|
- "9999:9999"
|
||||||
|
environment:
|
||||||
|
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka1:19092,EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9092,DOCKER://host.docker.internal:29092
|
||||||
|
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,DOCKER:PLAINTEXT
|
||||||
|
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
|
||||||
|
KAFKA_ZOOKEEPER_CONNECT: "zoo1:2181"
|
||||||
|
KAFKA_BROKER_ID: 1
|
||||||
|
KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO"
|
||||||
|
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
|
||||||
|
KAFKA_JMX_PORT: 9999
|
||||||
|
KAFKA_JMX_HOSTNAME: ${DOCKER_HOST_IP:-127.0.0.1}
|
||||||
|
KAFKA_AUTHORIZER_CLASS_NAME: kafka.security.authorizer.AclAuthorizer
|
||||||
|
KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND: "true"
|
||||||
|
depends_on:
|
||||||
|
- zoo1
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
|
||||||
|
kafka-ui:
|
||||||
|
container_name: kafka-ui
|
||||||
|
image: provectuslabs/kafka-ui:latest
|
||||||
|
ports:
|
||||||
|
- 8087:8080
|
||||||
|
environment:
|
||||||
|
DYNAMIC_CONFIG_ENABLED: true
|
||||||
|
volumes:
|
||||||
|
- /Users/rishi/work/config/kafka-ui/config.yml:/etc/kafkaui/dynamic_config.yaml
|
||||||
|
depends_on:
|
||||||
|
- kafka1
|
||||||
|
- zoo1
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
|
||||||
|
db:
|
||||||
|
image: "mongo:latest"
|
||||||
|
container_name: database
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
volumes:
|
||||||
|
- "mongodb_data:/bitnami/mongodb"
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: "bitnami/redis:latest"
|
||||||
|
container_name: queue
|
||||||
|
environment:
|
||||||
|
ALLOW_EMPTY_PASSWORD: "yes"
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
|
||||||
|
elasticsearch:
|
||||||
|
image: docker.elastic.co/elasticsearch/elasticsearch:7.16.2
|
||||||
|
container_name: elasticsearch
|
||||||
|
environment:
|
||||||
|
- "discovery.type=single-node"
|
||||||
|
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
|
||||||
|
- "xpack.security.enabled=true"
|
||||||
|
- "xpack.security.authc.api_key.enabled=true"
|
||||||
|
- "ELASTIC_PASSWORD=password"
|
||||||
|
ulimits:
|
||||||
|
memlock:
|
||||||
|
soft: -1
|
||||||
|
hard: -1
|
||||||
|
ports:
|
||||||
|
- "9200:9200"
|
||||||
|
networks:
|
||||||
|
- kafka-net
|
||||||
|
|
||||||
|
networks:
|
||||||
|
kafka-net:
|
||||||
|
driver: bridge
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mongodb_data:
|
||||||
|
driver: local
|
||||||
|
elasticsearch:
|
||||||
|
driver: local
|
||||||
@@ -3,7 +3,15 @@ LOGGER=true
|
|||||||
LOGLEVEL=info
|
LOGLEVEL=info
|
||||||
SERVICEDIR=dist/services
|
SERVICEDIR=dist/services
|
||||||
|
|
||||||
TRANSPORTER=nats://nats:4222
|
VITE_UNDERLYING_HOST=localhost
|
||||||
|
COMICS_DIRECTORY=/Users/rishi/work/threetwo-core-service/comics
|
||||||
|
USERDATA_DIRECTORY=/Users/rishi/work/threetwo-core-service/userdata
|
||||||
|
REDIS_URI=redis://redis:6379
|
||||||
|
KAFKA_BROKER=kafka1:9092
|
||||||
|
ELASTICSEARCH_URI=http://elasticsearch:9200
|
||||||
|
MONGO_URI=mongodb://db:27017/threetwo
|
||||||
|
UNRAR_BIN_PATH=/opt/homebrew/bin/unrar
|
||||||
|
SEVENZ_BINARY_PATH=/opt/homebrew/bin/7za
|
||||||
|
|
||||||
CACHER=Memory
|
CACHER=Memory
|
||||||
|
|
||||||
|
|||||||
@@ -1,58 +1,125 @@
|
|||||||
version: "3.3"
|
x-userdata-volume: &userdata-volume
|
||||||
|
type: bind
|
||||||
|
source: ${USERDATA_DIRECTORY}
|
||||||
|
target: /userdata
|
||||||
|
|
||||||
|
x-comics-volume: &comics-volume
|
||||||
|
type: bind
|
||||||
|
source: ${COMICS_DIRECTORY}
|
||||||
|
target: /comics
|
||||||
|
|
||||||
services:
|
services:
|
||||||
|
core-services:
|
||||||
api:
|
|
||||||
build:
|
build:
|
||||||
context: .
|
# context: https://github.com/rishighan/threetwo-core-service.git
|
||||||
image: threetwo-library-service
|
context: ./
|
||||||
env_file: docker-compose.env
|
dockerfile: Dockerfile
|
||||||
environment:
|
image: frishi/threetwo-core-service
|
||||||
SERVICES: api
|
container_name: core-services
|
||||||
PORT: 3000
|
|
||||||
depends_on:
|
|
||||||
- nats
|
|
||||||
labels:
|
|
||||||
- "traefik.enable=true"
|
|
||||||
- "traefik.http.routers.api-gw.rule=PathPrefix(`/`)"
|
|
||||||
- "traefik.http.services.api-gw.loadbalancer.server.port=3000"
|
|
||||||
networks:
|
|
||||||
- internal
|
|
||||||
|
|
||||||
greeter:
|
|
||||||
build:
|
|
||||||
context: .
|
|
||||||
image: threetwo-library-service
|
|
||||||
env_file: docker-compose.env
|
|
||||||
environment:
|
|
||||||
SERVICES: greeter
|
|
||||||
depends_on:
|
|
||||||
- nats
|
|
||||||
networks:
|
|
||||||
- internal
|
|
||||||
|
|
||||||
nats:
|
|
||||||
image: nats:2
|
|
||||||
networks:
|
|
||||||
- internal
|
|
||||||
|
|
||||||
traefik:
|
|
||||||
image: traefik:v2.1
|
|
||||||
command:
|
|
||||||
- "--api.insecure=true" # Don't do that in production!
|
|
||||||
- "--providers.docker=true"
|
|
||||||
- "--providers.docker.exposedbydefault=false"
|
|
||||||
ports:
|
ports:
|
||||||
- 3000:80
|
- "3000:3000"
|
||||||
- 3001:8080
|
- "3001:3001"
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
|
- redis
|
||||||
|
- elasticsearch
|
||||||
|
- kafka1
|
||||||
|
- zoo1
|
||||||
|
environment:
|
||||||
|
name: core-services
|
||||||
|
SERVICES: api,library,imagetransformation,opds,search,settings,jobqueue,socket,torrentjobs
|
||||||
|
env_file: docker-compose.env
|
||||||
volumes:
|
volumes:
|
||||||
- /var/run/docker.sock:/var/run/docker.sock:ro
|
- *comics-volume
|
||||||
|
- *userdata-volume
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- proxy
|
||||||
- default
|
|
||||||
|
zoo1:
|
||||||
|
image: confluentinc/cp-zookeeper:7.3.2
|
||||||
|
hostname: zoo1
|
||||||
|
container_name: zoo1
|
||||||
|
ports:
|
||||||
|
- "2181:2181"
|
||||||
|
environment:
|
||||||
|
ZOOKEEPER_CLIENT_PORT: 2181
|
||||||
|
ZOOKEEPER_SERVER_ID: 1
|
||||||
|
ZOOKEEPER_SERVERS: zoo1:2888:3888
|
||||||
|
networks:
|
||||||
|
- proxy
|
||||||
|
|
||||||
|
kafka1:
|
||||||
|
image: confluentinc/cp-kafka:7.3.2
|
||||||
|
hostname: kafka1
|
||||||
|
container_name: kafka1
|
||||||
|
ports:
|
||||||
|
- "9092:9092"
|
||||||
|
- "29092:29092"
|
||||||
|
- "9999:9999"
|
||||||
|
environment:
|
||||||
|
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka1:19092,EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1} :9092,DOCKER://host.docker.internal:29092
|
||||||
|
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,DOCKER:PLAINTEXT
|
||||||
|
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
|
||||||
|
KAFKA_ZOOKEEPER_CONNECT: "zoo1:2181"
|
||||||
|
KAFKA_BROKER_ID: 1
|
||||||
|
KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state. change.logger=INFO"
|
||||||
|
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
|
||||||
|
KAFKA_JMX_PORT: 9999
|
||||||
|
KAFKA_JMX_HOSTNAME: ${DOCKER_HOST_IP:-127.0.0.1}
|
||||||
|
KAFKA_AUTHORIZER_CLASS_NAME: kafka.security.authorizer.AclAuthorizer
|
||||||
|
KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND: "true"
|
||||||
|
depends_on:
|
||||||
|
- zoo1
|
||||||
|
networks:
|
||||||
|
- proxy
|
||||||
|
|
||||||
|
db:
|
||||||
|
image: "mongo:latest"
|
||||||
|
container_name: database
|
||||||
|
networks:
|
||||||
|
- proxy
|
||||||
|
ports:
|
||||||
|
- "27017:27017"
|
||||||
|
volumes:
|
||||||
|
- "mongodb_data:/bitnami/mongodb"
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: "bitnami/redis:latest"
|
||||||
|
container_name: redis
|
||||||
|
hostname: redis
|
||||||
|
environment:
|
||||||
|
ALLOW_EMPTY_PASSWORD: "yes"
|
||||||
|
networks:
|
||||||
|
- proxy
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
|
||||||
|
elasticsearch:
|
||||||
|
image: docker.elastic.co/elasticsearch/elasticsearch:7.16.2
|
||||||
|
container_name: elasticsearch
|
||||||
|
environment:
|
||||||
|
- "discovery.type=single-node"
|
||||||
|
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
|
||||||
|
- "xpack.security.enabled=true"
|
||||||
|
- "xpack.security.authc.api_key.enabled=true"
|
||||||
|
- "ELASTIC_PASSWORD=password"
|
||||||
|
ulimits:
|
||||||
|
memlock:
|
||||||
|
soft: -1
|
||||||
|
hard: -1
|
||||||
|
ports:
|
||||||
|
- 9200:9200
|
||||||
|
networks:
|
||||||
|
- proxy
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
internal:
|
proxy:
|
||||||
|
external: true
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
data:
|
mongodb_data:
|
||||||
|
driver: local
|
||||||
|
elasticsearch:
|
||||||
|
driver: local
|
||||||
|
|||||||
@@ -2,21 +2,60 @@ const path = require("path");
|
|||||||
const mkdir = require("mkdirp").sync;
|
const mkdir = require("mkdirp").sync;
|
||||||
const DbService = require("moleculer-db");
|
const DbService = require("moleculer-db");
|
||||||
|
|
||||||
|
|
||||||
export const DbMixin = (collection, model) => {
|
export const DbMixin = (collection, model) => {
|
||||||
if (process.env.MONGO_URI) {
|
if (!process.env.MONGO_URI) {
|
||||||
const MongooseAdapter = require("moleculer-db-adapter-mongoose");
|
console.log("MONGO_URI not provided, initializing local storage...");
|
||||||
return {
|
mkdir(path.resolve("./data"));
|
||||||
mixins: [DbService],
|
return { mixins: [DbService] }; // Handle case where no DB URI is provided
|
||||||
adapter: new MongooseAdapter(process.env.MONGO_URI, {
|
|
||||||
user: process.env.MONGO_INITDB_ROOT_USERNAME,
|
|
||||||
pass: process.env.MONGO_INITDB_ROOT_PASSWORD,
|
|
||||||
keepAlive: true,
|
|
||||||
useUnifiedTopology: true,
|
|
||||||
family: 4,
|
|
||||||
}),
|
|
||||||
model,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
mkdir(path.resolve("./data"));
|
|
||||||
|
const MongooseAdapter = require("moleculer-db-adapter-mongoose");
|
||||||
|
const adapter = new MongooseAdapter(process.env.MONGO_URI, {
|
||||||
|
user: process.env.MONGO_INITDB_ROOT_USERNAME,
|
||||||
|
pass: process.env.MONGO_INITDB_ROOT_PASSWORD,
|
||||||
|
keepAlive: true,
|
||||||
|
useNewUrlParser: true,
|
||||||
|
useUnifiedTopology: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const connectWithRetry = async (
|
||||||
|
adapter,
|
||||||
|
maxRetries = 5,
|
||||||
|
interval = 5000
|
||||||
|
) => {
|
||||||
|
for (let retry = 0; retry < maxRetries; retry++) {
|
||||||
|
try {
|
||||||
|
await adapter.connect();
|
||||||
|
console.log("MongoDB connected successfully!");
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("MongoDB connection error:", err);
|
||||||
|
console.log(
|
||||||
|
`Retrying MongoDB connection in ${
|
||||||
|
interval / 1000
|
||||||
|
} seconds...`
|
||||||
|
);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, interval));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.error("Failed to connect to MongoDB after several attempts.");
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
mixins: [DbService],
|
||||||
|
adapter,
|
||||||
|
model,
|
||||||
|
collection,
|
||||||
|
async started() {
|
||||||
|
await connectWithRetry(this.adapter);
|
||||||
|
},
|
||||||
|
async stopped() {
|
||||||
|
try {
|
||||||
|
await this.adapter.disconnect();
|
||||||
|
console.log("MongoDB disconnected");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("MongoDB disconnection error:", err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
const paginate = require("mongoose-paginate-v2");
|
const paginate = require("mongoose-paginate-v2");
|
||||||
const { Client } = require("@elastic/elasticsearch");
|
const { Client } = require("@elastic/elasticsearch");
|
||||||
import ComicVineMetadataSchema from "./comicvine.metadata.model";
|
|
||||||
import { mongoosastic } from "mongoosastic-ts";
|
import { mongoosastic } from "mongoosastic-ts";
|
||||||
const mongoose = require("mongoose")
|
const mongoose = require("mongoose");
|
||||||
import {
|
import {
|
||||||
MongoosasticDocument,
|
MongoosasticDocument,
|
||||||
MongoosasticModel,
|
MongoosasticModel,
|
||||||
@@ -28,6 +27,10 @@ const RawFileDetailsSchema = mongoose.Schema({
|
|||||||
mimeType: String,
|
mimeType: String,
|
||||||
containedIn: String,
|
containedIn: String,
|
||||||
pageCount: Number,
|
pageCount: Number,
|
||||||
|
archive: {
|
||||||
|
uncompressed: Boolean,
|
||||||
|
expandedPath: String,
|
||||||
|
},
|
||||||
cover: {
|
cover: {
|
||||||
filePath: String,
|
filePath: String,
|
||||||
stats: Object,
|
stats: Object,
|
||||||
@@ -51,7 +54,38 @@ const DirectConnectBundleSchema = mongoose.Schema({
|
|||||||
name: String,
|
name: String,
|
||||||
size: String,
|
size: String,
|
||||||
type: {},
|
type: {},
|
||||||
|
_id: false,
|
||||||
});
|
});
|
||||||
|
const wantedSchema = mongoose.Schema(
|
||||||
|
{
|
||||||
|
source: { type: String, default: null },
|
||||||
|
markEntireVolumeWanted: Boolean,
|
||||||
|
issues: {
|
||||||
|
type: [
|
||||||
|
{
|
||||||
|
_id: false, // Disable automatic ObjectId creation for each issue
|
||||||
|
id: Number,
|
||||||
|
url: String,
|
||||||
|
image: { type: Array, default: [] },
|
||||||
|
coverDate: String,
|
||||||
|
issueNumber: String,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
volume: {
|
||||||
|
type: {
|
||||||
|
_id: false, // Disable automatic ObjectId creation for volume
|
||||||
|
id: Number,
|
||||||
|
url: String,
|
||||||
|
image: { type: Array, default: [] },
|
||||||
|
name: String,
|
||||||
|
},
|
||||||
|
default: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ _id: false }
|
||||||
|
); // Disable automatic ObjectId creation for the wanted object itself
|
||||||
|
|
||||||
const ComicSchema = mongoose.Schema(
|
const ComicSchema = mongoose.Schema(
|
||||||
{
|
{
|
||||||
@@ -67,18 +101,12 @@ const ComicSchema = mongoose.Schema(
|
|||||||
},
|
},
|
||||||
sourcedMetadata: {
|
sourcedMetadata: {
|
||||||
comicInfo: { type: mongoose.Schema.Types.Mixed, default: {} },
|
comicInfo: { type: mongoose.Schema.Types.Mixed, default: {} },
|
||||||
comicvine: {
|
comicvine: { type: mongoose.Schema.Types.Mixed, default: {} }, // Set as a freeform object
|
||||||
type: ComicVineMetadataSchema,
|
|
||||||
es_indexed: true,
|
|
||||||
default: {},
|
|
||||||
},
|
|
||||||
shortboxed: {},
|
|
||||||
locg: {
|
locg: {
|
||||||
type: LOCGSchema,
|
type: LOCGSchema,
|
||||||
es_indexed: true,
|
es_indexed: true,
|
||||||
default: {},
|
default: {},
|
||||||
},
|
},
|
||||||
gcd: {},
|
|
||||||
},
|
},
|
||||||
rawFileDetails: {
|
rawFileDetails: {
|
||||||
type: RawFileDetailsSchema,
|
type: RawFileDetailsSchema,
|
||||||
@@ -98,11 +126,9 @@ const ComicSchema = mongoose.Schema(
|
|||||||
subtitle: { type: String, es_indexed: true },
|
subtitle: { type: String, es_indexed: true },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
wanted: wantedSchema,
|
||||||
|
|
||||||
acquisition: {
|
acquisition: {
|
||||||
source: {
|
|
||||||
wanted: Boolean,
|
|
||||||
name: String,
|
|
||||||
},
|
|
||||||
release: {},
|
release: {},
|
||||||
directconnect: {
|
directconnect: {
|
||||||
downloads: {
|
downloads: {
|
||||||
@@ -111,12 +137,13 @@ const ComicSchema = mongoose.Schema(
|
|||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
torrent: {
|
torrent: [
|
||||||
sourceApplication: String,
|
{
|
||||||
magnet: String,
|
infoHash: String,
|
||||||
tracker: String,
|
name: String,
|
||||||
status: String,
|
announce: [String],
|
||||||
},
|
},
|
||||||
|
],
|
||||||
usenet: {
|
usenet: {
|
||||||
sourceApplication: String,
|
sourceApplication: String,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
const mongoose = require("mongoose");
|
|
||||||
const Things = mongoose.Schema({
|
|
||||||
_id: false,
|
|
||||||
api_detail_url: String,
|
|
||||||
id: Number,
|
|
||||||
name: String,
|
|
||||||
site_detail_url: String,
|
|
||||||
count: String,
|
|
||||||
});
|
|
||||||
const Issue = mongoose.Schema({
|
|
||||||
_id: false,
|
|
||||||
api_detail_url: String,
|
|
||||||
id: Number,
|
|
||||||
name: String,
|
|
||||||
issue_number: String,
|
|
||||||
});
|
|
||||||
const VolumeInformation = mongoose.Schema({
|
|
||||||
_id: false,
|
|
||||||
aliases: [String],
|
|
||||||
api_detail_url: String,
|
|
||||||
characters: [Things],
|
|
||||||
concepts: [Things],
|
|
||||||
count_of_issues: String,
|
|
||||||
date_added: String,
|
|
||||||
date_last_updated: String,
|
|
||||||
deck: String,
|
|
||||||
description: String,
|
|
||||||
first_issue: Issue,
|
|
||||||
id: Number,
|
|
||||||
image: {
|
|
||||||
icon_url: String,
|
|
||||||
medium_url: String,
|
|
||||||
screen_url: String,
|
|
||||||
screen_large_url: String,
|
|
||||||
small_url: String,
|
|
||||||
super_url: String,
|
|
||||||
thumb_url: String,
|
|
||||||
tiny_url: String,
|
|
||||||
original_url: String,
|
|
||||||
image_tags: String,
|
|
||||||
},
|
|
||||||
issues: [
|
|
||||||
{
|
|
||||||
api_detail_url: String,
|
|
||||||
id: Number,
|
|
||||||
name: String,
|
|
||||||
issue_number: String,
|
|
||||||
site_detail_url: String,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
last_issue: Issue,
|
|
||||||
locations: [Things],
|
|
||||||
name: String,
|
|
||||||
objects: [Things],
|
|
||||||
people: [Things],
|
|
||||||
publisher: {
|
|
||||||
api_detail_url: String,
|
|
||||||
id: Number,
|
|
||||||
name: String,
|
|
||||||
},
|
|
||||||
site_detail_url: String,
|
|
||||||
start_year: String,
|
|
||||||
});
|
|
||||||
|
|
||||||
const ComicVineMetadataSchema = mongoose.Schema({
|
|
||||||
_id: false,
|
|
||||||
aliases: [String],
|
|
||||||
api_detail_url: String,
|
|
||||||
has_staff_review: { type: mongoose.Schema.Types.Mixed },
|
|
||||||
|
|
||||||
cover_date: Date,
|
|
||||||
date_added: String,
|
|
||||||
date_last_updated: String,
|
|
||||||
deck: String,
|
|
||||||
description: String,
|
|
||||||
image: {
|
|
||||||
icon_url: String,
|
|
||||||
medium_url: String,
|
|
||||||
screen_url: String,
|
|
||||||
screen_large_url: String,
|
|
||||||
small_url: String,
|
|
||||||
super_url: String,
|
|
||||||
thumb_url: String,
|
|
||||||
tiny_url: String,
|
|
||||||
original_url: String,
|
|
||||||
image_tags: String,
|
|
||||||
},
|
|
||||||
|
|
||||||
id: Number,
|
|
||||||
name: String,
|
|
||||||
resource_type: String,
|
|
||||||
volumeInformation: VolumeInformation,
|
|
||||||
});
|
|
||||||
|
|
||||||
export default ComicVineMetadataSchema;
|
|
||||||
@@ -1,21 +1,34 @@
|
|||||||
const mongoose = require("mongoose");
|
const mongoose = require("mongoose");
|
||||||
const paginate = require("mongoose-paginate-v2");
|
const paginate = require("mongoose-paginate-v2");
|
||||||
|
|
||||||
|
const HostSchema = mongoose.Schema({
|
||||||
|
_id: false,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
hostname: String,
|
||||||
|
port: String,
|
||||||
|
protocol: String,
|
||||||
|
});
|
||||||
const SettingsScehma = mongoose.Schema({
|
const SettingsScehma = mongoose.Schema({
|
||||||
directConnect: {
|
directConnect: {
|
||||||
client: {
|
client: {
|
||||||
host: {
|
host: HostSchema,
|
||||||
username: String,
|
|
||||||
password: String,
|
|
||||||
hostname: String,
|
|
||||||
port: String,
|
|
||||||
protocol: String,
|
|
||||||
},
|
|
||||||
airDCPPUserSettings: Object,
|
airDCPPUserSettings: Object,
|
||||||
|
|
||||||
hubs: Array,
|
hubs: Array,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
bittorrent: {
|
||||||
|
client: {
|
||||||
|
name: String,
|
||||||
|
host: HostSchema,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
prowlarr: {
|
||||||
|
client: {
|
||||||
|
host: HostSchema,
|
||||||
|
apiKey: String,
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const Settings = mongoose.model("Settings", SettingsScehma);
|
const Settings = mongoose.model("Settings", SettingsScehma);
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
MetricRegistry,
|
MetricRegistry,
|
||||||
ServiceBroker,
|
ServiceBroker,
|
||||||
} from "moleculer";
|
} from "moleculer";
|
||||||
|
const RedisTransporter = require("moleculer").Transporters.Redis;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Moleculer ServiceBroker configuration file
|
* Moleculer ServiceBroker configuration file
|
||||||
@@ -90,7 +91,7 @@ const brokerConfig: BrokerOptions = {
|
|||||||
// More info: https://moleculer.services/docs/0.14/networking.html
|
// More info: https://moleculer.services/docs/0.14/networking.html
|
||||||
// Note: During the development, you don't need to define it because all services will be loaded locally.
|
// Note: During the development, you don't need to define it because all services will be loaded locally.
|
||||||
// In production you can set it via `TRANSPORTER=nats://localhost:4222` environment variable.
|
// In production you can set it via `TRANSPORTER=nats://localhost:4222` environment variable.
|
||||||
transporter: process.env.REDIS_URI || "redis://localhost:6379",
|
transporter: new RedisTransporter(process.env.REDIS_URI),
|
||||||
|
|
||||||
// Define a cacher.
|
// Define a cacher.
|
||||||
// More info: https://moleculer.services/docs/0.14/caching.html
|
// More info: https://moleculer.services/docs/0.14/caching.html
|
||||||
|
|||||||
3164
package-lock.json
generated
3164
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
@@ -4,8 +4,8 @@
|
|||||||
"description": "Endpoints for common operations in ThreeTwo",
|
"description": "Endpoints for common operations in ThreeTwo",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc --build tsconfig.json",
|
"build": "tsc --build tsconfig.json",
|
||||||
"dev": "ts-node ./node_modules/moleculer/bin/moleculer-runner.js --hot --repl --config moleculer.config.ts services/**/*.service.ts",
|
"dev": "./scripts/start.sh dev",
|
||||||
"start": "moleculer-runner --config dist/moleculer.config.js",
|
"start": "npm run build && ./scripts/start.sh prod",
|
||||||
"cli": "moleculer connect NATS",
|
"cli": "moleculer connect NATS",
|
||||||
"ci": "jest --watch",
|
"ci": "jest --watch",
|
||||||
"test": "jest --coverage",
|
"test": "jest --coverage",
|
||||||
@@ -27,6 +27,7 @@
|
|||||||
"eslint-plugin-import": "^2.20.2",
|
"eslint-plugin-import": "^2.20.2",
|
||||||
"eslint-plugin-prefer-arrow": "^1.2.2",
|
"eslint-plugin-prefer-arrow": "^1.2.2",
|
||||||
"install": "^0.13.0",
|
"install": "^0.13.0",
|
||||||
|
"ioredis": "^5.4.1",
|
||||||
"jest": "^29.5.0",
|
"jest": "^29.5.0",
|
||||||
"jest-cli": "^29.5.0",
|
"jest-cli": "^29.5.0",
|
||||||
"moleculer-repl": "^0.7.0",
|
"moleculer-repl": "^0.7.0",
|
||||||
@@ -39,7 +40,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@bluelovers/fast-glob": "https://github.com/rishighan/fast-glob-v2-api.git",
|
"@bluelovers/fast-glob": "https://github.com/rishighan/fast-glob-v2-api.git",
|
||||||
"@elastic/elasticsearch": "^8.6.0",
|
"@elastic/elasticsearch": "^8.13.1",
|
||||||
"@jorgeferrero/stream-to-buffer": "^2.0.6",
|
"@jorgeferrero/stream-to-buffer": "^2.0.6",
|
||||||
"@npcz/magic": "^1.3.14",
|
"@npcz/magic": "^1.3.14",
|
||||||
"@root/walk": "^1.1.0",
|
"@root/walk": "^1.1.0",
|
||||||
@@ -48,7 +49,8 @@
|
|||||||
"@types/mkdirp": "^1.0.0",
|
"@types/mkdirp": "^1.0.0",
|
||||||
"@types/node": "^13.9.8",
|
"@types/node": "^13.9.8",
|
||||||
"@types/string-similarity": "^4.0.0",
|
"@types/string-similarity": "^4.0.0",
|
||||||
"axios": "^0.25.0",
|
"airdcpp-apisocket": "^2.4.4",
|
||||||
|
"axios": "^1.6.8",
|
||||||
"axios-retry": "^3.2.4",
|
"axios-retry": "^3.2.4",
|
||||||
"bree": "^7.1.5",
|
"bree": "^7.1.5",
|
||||||
"calibre-opds": "^1.0.7",
|
"calibre-opds": "^1.0.7",
|
||||||
@@ -67,22 +69,22 @@
|
|||||||
"mkdirp": "^0.5.5",
|
"mkdirp": "^0.5.5",
|
||||||
"moleculer-bullmq": "^3.0.0",
|
"moleculer-bullmq": "^3.0.0",
|
||||||
"moleculer-db": "^0.8.23",
|
"moleculer-db": "^0.8.23",
|
||||||
"moleculer-db-adapter-mongoose": "^0.9.2",
|
"moleculer-db-adapter-mongoose": "^0.9.4",
|
||||||
"moleculer-io": "^2.2.0",
|
"moleculer-io": "^2.2.0",
|
||||||
"moleculer-web": "^0.10.5",
|
"moleculer-web": "^0.10.7",
|
||||||
"mongoosastic-ts": "^6.0.3",
|
"mongoosastic-ts": "^6.0.3",
|
||||||
"mongoose": "^6.10.4",
|
"mongoose": "^6.10.4",
|
||||||
"mongoose-paginate-v2": "^1.3.18",
|
"mongoose-paginate-v2": "^1.3.18",
|
||||||
"nats": "^1.3.2",
|
"nats": "^1.3.2",
|
||||||
"opds-extra": "^3.0.9",
|
"opds-extra": "^3.0.10",
|
||||||
"p7zip-threetwo": "^1.0.4",
|
"p7zip-threetwo": "^1.0.4",
|
||||||
"redis": "^4.6.5",
|
"redis": "^4.6.14",
|
||||||
"sanitize-filename-ts": "^1.0.2",
|
"sanitize-filename-ts": "^1.0.2",
|
||||||
"sharp": "^0.30.4",
|
"sharp": "^0.33.3",
|
||||||
"threetwo-ui-typings": "^1.0.14",
|
"threetwo-ui-typings": "^1.0.14",
|
||||||
"through2": "^4.0.2",
|
"through2": "^4.0.2",
|
||||||
"unrar": "^0.2.0",
|
"unrar": "^0.2.0",
|
||||||
"xml2js": "^0.4.23"
|
"xml2js": "^0.6.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 18.x.x"
|
"node": ">= 18.x.x"
|
||||||
|
|||||||
26
scripts/start.sh
Executable file
26
scripts/start.sh
Executable file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
echo "Starting script with mode: $MODE"
|
||||||
|
|
||||||
|
# Extract the host and port from MONGO_URI
|
||||||
|
HOST_PORT=$(echo $MONGO_URI | sed -e 's/mongodb:\/\///' -e 's/\/.*$//')
|
||||||
|
|
||||||
|
# Assuming the script is called from the project root
|
||||||
|
PROJECT_ROOT=$(pwd)
|
||||||
|
echo "Project root: $PROJECT_ROOT"
|
||||||
|
|
||||||
|
CONFIG_PATH="$PROJECT_ROOT/moleculer.config.ts"
|
||||||
|
echo "Configuration path: $CONFIG_PATH"
|
||||||
|
|
||||||
|
# Set the correct path for moleculer-runner based on the mode
|
||||||
|
if [ "$MODE" == "dev" ]; then
|
||||||
|
# For development: use ts-node
|
||||||
|
MOLECULER_RUNNER="ts-node $PROJECT_ROOT/node_modules/moleculer/bin/moleculer-runner.js --hot --repl --config $CONFIG_PATH $PROJECT_ROOT/services/**/*.service.ts"
|
||||||
|
echo "Moleculer Runner for dev: $MOLECULER_RUNNER"
|
||||||
|
else
|
||||||
|
# For production: direct node execution of the compiled JavaScript
|
||||||
|
MOLECULER_RUNNER="moleculer-runner --config $PROJECT_ROOT/dist/moleculer.config.js $PROJECT_ROOT/dist/services/**/*.service.js"
|
||||||
|
echo "Moleculer Runner for prod: $MOLECULER_RUNNER"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Run wait-for-it, then start the application
|
||||||
|
./scripts/wait-for-it.sh $HOST_PORT -- $MOLECULER_RUNNER
|
||||||
190
scripts/wait-for-it.sh
Executable file
190
scripts/wait-for-it.sh
Executable file
@@ -0,0 +1,190 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Use this script to test if a given TCP host/port are available
|
||||||
|
|
||||||
|
WAITFORIT_cmdname=${0##*/}
|
||||||
|
if [[ $OSTYPE == 'darwin'* ]]; then
|
||||||
|
if ! command -v gtimeout &> /dev/null
|
||||||
|
then
|
||||||
|
echo "missing gtimeout (`brew install coreutils`)"
|
||||||
|
exit
|
||||||
|
fi
|
||||||
|
alias timeout=gtimeout
|
||||||
|
fi
|
||||||
|
|
||||||
|
echoerr() { if [[ $WAITFORIT_QUIET -ne 1 ]]; then echo "$@" 1>&2; fi }
|
||||||
|
|
||||||
|
usage()
|
||||||
|
{
|
||||||
|
cat << USAGE >&2
|
||||||
|
Usage:
|
||||||
|
$WAITFORIT_cmdname host:port [-s] [-t timeout] [-- command args]
|
||||||
|
-h HOST | --host=HOST Host or IP under test
|
||||||
|
-p PORT | --port=PORT TCP port under test
|
||||||
|
Alternatively, you specify the host and port as host:port
|
||||||
|
-s | --strict Only execute subcommand if the test succeeds
|
||||||
|
-q | --quiet Don't output any status messages
|
||||||
|
-t TIMEOUT | --timeout=TIMEOUT
|
||||||
|
Timeout in seconds, zero for no timeout
|
||||||
|
-- COMMAND ARGS Execute command with args after the test finishes
|
||||||
|
USAGE
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for()
|
||||||
|
{
|
||||||
|
if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
|
||||||
|
echoerr "$WAITFORIT_cmdname: waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
|
||||||
|
else
|
||||||
|
echoerr "$WAITFORIT_cmdname: waiting for $WAITFORIT_HOST:$WAITFORIT_PORT without a timeout"
|
||||||
|
fi
|
||||||
|
WAITFORIT_start_ts=$(date +%s)
|
||||||
|
while :
|
||||||
|
do
|
||||||
|
if [[ $WAITFORIT_ISBUSY -eq 1 ]]; then
|
||||||
|
nc -z $WAITFORIT_HOST $WAITFORIT_PORT
|
||||||
|
WAITFORIT_result=$?
|
||||||
|
else
|
||||||
|
(echo -n > /dev/tcp/$WAITFORIT_HOST/$WAITFORIT_PORT) >/dev/null 2>&1
|
||||||
|
WAITFORIT_result=$?
|
||||||
|
fi
|
||||||
|
if [[ $WAITFORIT_result -eq 0 ]]; then
|
||||||
|
WAITFORIT_end_ts=$(date +%s)
|
||||||
|
echoerr "$WAITFORIT_cmdname: $WAITFORIT_HOST:$WAITFORIT_PORT is available after $((WAITFORIT_end_ts - WAITFORIT_start_ts)) seconds"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
return $WAITFORIT_result
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_wrapper()
|
||||||
|
{
|
||||||
|
# In order to support SIGINT during timeout: http://unix.stackexchange.com/a/57692
|
||||||
|
if [[ $WAITFORIT_QUIET -eq 1 ]]; then
|
||||||
|
timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --quiet --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
|
||||||
|
else
|
||||||
|
timeout $WAITFORIT_BUSYTIMEFLAG $WAITFORIT_TIMEOUT $0 --child --host=$WAITFORIT_HOST --port=$WAITFORIT_PORT --timeout=$WAITFORIT_TIMEOUT &
|
||||||
|
fi
|
||||||
|
WAITFORIT_PID=$!
|
||||||
|
trap "kill -INT -$WAITFORIT_PID" INT
|
||||||
|
wait $WAITFORIT_PID
|
||||||
|
WAITFORIT_RESULT=$?
|
||||||
|
if [[ $WAITFORIT_RESULT -ne 0 ]]; then
|
||||||
|
echoerr "$WAITFORIT_cmdname: timeout occurred after waiting $WAITFORIT_TIMEOUT seconds for $WAITFORIT_HOST:$WAITFORIT_PORT"
|
||||||
|
fi
|
||||||
|
return $WAITFORIT_RESULT
|
||||||
|
}
|
||||||
|
|
||||||
|
# process arguments
|
||||||
|
while [[ $# -gt 0 ]]
|
||||||
|
do
|
||||||
|
case "$1" in
|
||||||
|
*:* )
|
||||||
|
WAITFORIT_hostport=(${1//:/ })
|
||||||
|
WAITFORIT_HOST=${WAITFORIT_hostport[0]}
|
||||||
|
WAITFORIT_PORT=${WAITFORIT_hostport[1]}
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
--child)
|
||||||
|
WAITFORIT_CHILD=1
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
-q | --quiet)
|
||||||
|
WAITFORIT_QUIET=1
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
-s | --strict)
|
||||||
|
WAITFORIT_STRICT=1
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
-h)
|
||||||
|
WAITFORIT_HOST="$2"
|
||||||
|
if [[ $WAITFORIT_HOST == "" ]]; then break; fi
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--host=*)
|
||||||
|
WAITFORIT_HOST="${1#*=}"
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
-p)
|
||||||
|
WAITFORIT_PORT="$2"
|
||||||
|
if [[ $WAITFORIT_PORT == "" ]]; then break; fi
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--port=*)
|
||||||
|
WAITFORIT_PORT="${1#*=}"
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
-t)
|
||||||
|
WAITFORIT_TIMEOUT="$2"
|
||||||
|
if [[ $WAITFORIT_TIMEOUT == "" ]]; then break; fi
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
|
--timeout=*)
|
||||||
|
WAITFORIT_TIMEOUT="${1#*=}"
|
||||||
|
shift 1
|
||||||
|
;;
|
||||||
|
--)
|
||||||
|
shift
|
||||||
|
WAITFORIT_CLI=("$@")
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
--help)
|
||||||
|
usage
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echoerr "Unknown argument: $1"
|
||||||
|
usage
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ "$WAITFORIT_HOST" == "" || "$WAITFORIT_PORT" == "" ]]; then
|
||||||
|
echoerr "Error: you need to provide a host and port to test."
|
||||||
|
usage
|
||||||
|
fi
|
||||||
|
|
||||||
|
WAITFORIT_TIMEOUT=${WAITFORIT_TIMEOUT:-15}
|
||||||
|
WAITFORIT_STRICT=${WAITFORIT_STRICT:-0}
|
||||||
|
WAITFORIT_CHILD=${WAITFORIT_CHILD:-0}
|
||||||
|
WAITFORIT_QUIET=${WAITFORIT_QUIET:-0}
|
||||||
|
|
||||||
|
# Check to see if timeout is from busybox?
|
||||||
|
WAITFORIT_TIMEOUT_PATH=$(type -p timeout)
|
||||||
|
WAITFORIT_TIMEOUT_PATH=$(realpath $WAITFORIT_TIMEOUT_PATH 2>/dev/null || readlink -f $WAITFORIT_TIMEOUT_PATH)
|
||||||
|
|
||||||
|
WAITFORIT_BUSYTIMEFLAG=""
|
||||||
|
if [[ $WAITFORIT_TIMEOUT_PATH =~ "busybox" ]]; then
|
||||||
|
WAITFORIT_ISBUSY=1
|
||||||
|
# Check if busybox timeout uses -t flag
|
||||||
|
# (recent Alpine versions don't support -t anymore)
|
||||||
|
if timeout &>/dev/stdout | grep -q -e '-t '; then
|
||||||
|
WAITFORIT_BUSYTIMEFLAG="-t"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
WAITFORIT_ISBUSY=0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ $WAITFORIT_CHILD -gt 0 ]]; then
|
||||||
|
wait_for
|
||||||
|
WAITFORIT_RESULT=$?
|
||||||
|
exit $WAITFORIT_RESULT
|
||||||
|
else
|
||||||
|
if [[ $WAITFORIT_TIMEOUT -gt 0 ]]; then
|
||||||
|
wait_for_wrapper
|
||||||
|
WAITFORIT_RESULT=$?
|
||||||
|
else
|
||||||
|
wait_for
|
||||||
|
WAITFORIT_RESULT=$?
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ $WAITFORIT_CLI != "" ]]; then
|
||||||
|
if [[ $WAITFORIT_RESULT -ne 0 && $WAITFORIT_STRICT -eq 1 ]]; then
|
||||||
|
echoerr "$WAITFORIT_cmdname: strict mode, refusing to execute subprocess"
|
||||||
|
exit $WAITFORIT_RESULT
|
||||||
|
fi
|
||||||
|
exec "${WAITFORIT_CLI[@]}"
|
||||||
|
else
|
||||||
|
exit $WAITFORIT_RESULT
|
||||||
|
fi
|
||||||
156
services/airdcpp.service.ts
Normal file
156
services/airdcpp.service.ts
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
"use strict";
|
||||||
|
import {
|
||||||
|
Context,
|
||||||
|
Service,
|
||||||
|
ServiceBroker,
|
||||||
|
ServiceSchema,
|
||||||
|
Errors,
|
||||||
|
} from "moleculer";
|
||||||
|
import axios from "axios";
|
||||||
|
import AirDCPPSocket from "../shared/airdcpp.socket";
|
||||||
|
|
||||||
|
export default class AirDCPPService extends Service {
|
||||||
|
// @ts-ignore
|
||||||
|
public constructor(
|
||||||
|
public broker: ServiceBroker,
|
||||||
|
schema: ServiceSchema<{}> = { name: "airdcpp" }
|
||||||
|
) {
|
||||||
|
super(broker);
|
||||||
|
this.parseServiceSchema({
|
||||||
|
name: "airdcpp",
|
||||||
|
mixins: [],
|
||||||
|
hooks: {},
|
||||||
|
actions: {
|
||||||
|
initialize: {
|
||||||
|
rest: "POST /initialize",
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
host: {
|
||||||
|
hostname: string;
|
||||||
|
port: string;
|
||||||
|
protocol: string;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
};
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
host: {
|
||||||
|
hostname,
|
||||||
|
protocol,
|
||||||
|
port,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
},
|
||||||
|
} = ctx.params;
|
||||||
|
const airDCPPSocket = new AirDCPPSocket({
|
||||||
|
protocol,
|
||||||
|
hostname: `${hostname}:${port}`,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
return await airDCPPSocket.connect();
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
getHubs: {
|
||||||
|
rest: "POST /getHubs",
|
||||||
|
timeout: 70000,
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
host: {
|
||||||
|
hostname: string;
|
||||||
|
port: string;
|
||||||
|
protocol: string;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
};
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
const {
|
||||||
|
host: {
|
||||||
|
hostname,
|
||||||
|
port,
|
||||||
|
protocol,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
},
|
||||||
|
} = ctx.params;
|
||||||
|
try {
|
||||||
|
const airDCPPSocket = new AirDCPPSocket({
|
||||||
|
protocol,
|
||||||
|
hostname: `${hostname}:${port}`,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
await airDCPPSocket.connect();
|
||||||
|
return await airDCPPSocket.get(`hubs`);
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
search: {
|
||||||
|
rest: "POST /search",
|
||||||
|
timeout: 20000,
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
host: {
|
||||||
|
hostname;
|
||||||
|
port;
|
||||||
|
protocol;
|
||||||
|
username;
|
||||||
|
password;
|
||||||
|
};
|
||||||
|
dcppSearchQuery;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
host: {
|
||||||
|
hostname,
|
||||||
|
port,
|
||||||
|
protocol,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
},
|
||||||
|
dcppSearchQuery,
|
||||||
|
} = ctx.params;
|
||||||
|
const airDCPPSocket = new AirDCPPSocket({
|
||||||
|
protocol,
|
||||||
|
hostname: `${hostname}:${port}`,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
await airDCPPSocket.connect();
|
||||||
|
const searchInstance = await airDCPPSocket.post(
|
||||||
|
`search`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Post the search
|
||||||
|
const searchInfo = await airDCPPSocket.post(
|
||||||
|
`search/${searchInstance.id}/hub_search`,
|
||||||
|
dcppSearchQuery
|
||||||
|
);
|
||||||
|
await this.sleep(10000);
|
||||||
|
const results = await airDCPPSocket.get(
|
||||||
|
`search/${searchInstance.id}/results/0/5`
|
||||||
|
);
|
||||||
|
return results;
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
sleep: (ms: number) => {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
ServiceSchema,
|
ServiceSchema,
|
||||||
Errors,
|
Errors,
|
||||||
} from "moleculer";
|
} from "moleculer";
|
||||||
|
import { DbMixin } from "../mixins/db.mixin";
|
||||||
|
import Comic from "../models/comic.model";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import {
|
import {
|
||||||
analyze,
|
analyze,
|
||||||
@@ -22,16 +24,13 @@ export default class ImageTransformation extends Service {
|
|||||||
super(broker);
|
super(broker);
|
||||||
this.parseServiceSchema({
|
this.parseServiceSchema({
|
||||||
name: "imagetransformation",
|
name: "imagetransformation",
|
||||||
mixins: [],
|
mixins: [DbMixin("comics", Comic)],
|
||||||
settings: {
|
settings: {
|
||||||
// Available fields in the responses
|
// Available fields in the responses
|
||||||
fields: ["_id", "name", "quantity", "price"],
|
fields: ["_id"],
|
||||||
|
|
||||||
// Validator for the `create` & `insert` actions.
|
// Validator for the `create` & `insert` actions.
|
||||||
entityValidator: {
|
entityValidator: {},
|
||||||
name: "string|min:3",
|
|
||||||
price: "number|positive",
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
hooks: {},
|
hooks: {},
|
||||||
actions: {
|
actions: {
|
||||||
|
|||||||
@@ -2,23 +2,29 @@ import { Context, Service, ServiceBroker } from "moleculer";
|
|||||||
import JobResult from "../models/jobresult.model";
|
import JobResult from "../models/jobresult.model";
|
||||||
import { refineQuery } from "filename-parser";
|
import { refineQuery } from "filename-parser";
|
||||||
import BullMqMixin from "moleculer-bullmq";
|
import BullMqMixin from "moleculer-bullmq";
|
||||||
import { extractFromArchive } from "../utils/uncompression.utils";
|
import { DbMixin } from "../mixins/db.mixin";
|
||||||
|
import Comic from "../models/comic.model";
|
||||||
|
const ObjectId = require("mongoose").Types.ObjectId;
|
||||||
|
import {
|
||||||
|
extractFromArchive,
|
||||||
|
uncompressEntireArchive,
|
||||||
|
} from "../utils/uncompression.utils";
|
||||||
import { isNil, isUndefined } from "lodash";
|
import { isNil, isUndefined } from "lodash";
|
||||||
import { pubClient } from "../config/redis.config";
|
import { pubClient } from "../config/redis.config";
|
||||||
|
import path from "path";
|
||||||
const { MoleculerError } = require("moleculer").Errors;
|
const { MoleculerError } = require("moleculer").Errors;
|
||||||
|
|
||||||
console.log(process.env.REDIS_URI);
|
|
||||||
export default class JobQueueService extends Service {
|
export default class JobQueueService extends Service {
|
||||||
public constructor(public broker: ServiceBroker) {
|
public constructor(public broker: ServiceBroker) {
|
||||||
super(broker);
|
super(broker);
|
||||||
this.parseServiceSchema({
|
this.parseServiceSchema({
|
||||||
name: "jobqueue",
|
name: "jobqueue",
|
||||||
hooks: {},
|
hooks: {},
|
||||||
mixins: [BullMqMixin],
|
mixins: [DbMixin("comics", Comic), BullMqMixin],
|
||||||
|
|
||||||
settings: {
|
settings: {
|
||||||
bullmq: {
|
bullmq: {
|
||||||
client: process.env.REDIS_URI,
|
client: pubClient,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
actions: {
|
actions: {
|
||||||
@@ -44,19 +50,34 @@ export default class JobQueueService extends Service {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
enqueue: {
|
enqueue: {
|
||||||
queue: true,
|
queue: true,
|
||||||
rest: "/GET enqueue",
|
rest: "GET /enqueue",
|
||||||
handler: async (ctx: Context<{}>) => {
|
handler: async (
|
||||||
// Enqueue the job
|
ctx: Context<{ action: string; description: string }>
|
||||||
const job = await this.localQueue(ctx, "enqueue.async", ctx.params, {
|
) => {
|
||||||
priority: 10,
|
try {
|
||||||
});
|
const { action, description } = ctx.params;
|
||||||
console.log(`Job ${job.id} enqueued`);
|
// Enqueue the job
|
||||||
|
const job = await this.localQueue(
|
||||||
|
ctx,
|
||||||
|
action,
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
priority: 10,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
console.log(`Job ${job.id} enqueued`);
|
||||||
|
console.log(`${description}`);
|
||||||
|
|
||||||
return job.id;
|
return job.id;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to enqueue job:", error);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
// Comic Book Import Job Queue
|
// Comic Book Import Job Queue
|
||||||
"enqueue.async": {
|
"enqueue.async": {
|
||||||
handler: async (
|
handler: async (
|
||||||
@@ -65,13 +86,16 @@ export default class JobQueueService extends Service {
|
|||||||
}>
|
}>
|
||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
console.log(`Recieved Job ID ${ctx.locals.job.id}, processing...`);
|
console.log(
|
||||||
console.log(ctx.params);
|
`Recieved Job ID ${ctx.locals.job.id}, processing...`
|
||||||
|
);
|
||||||
// 1. De-structure the job params
|
// 1. De-structure the job params
|
||||||
const { fileObject } = ctx.locals.job.data.params;
|
const { fileObject } = ctx.locals.job.data.params;
|
||||||
|
|
||||||
// 2. Extract metadata from the archive
|
// 2. Extract metadata from the archive
|
||||||
const result = await extractFromArchive(fileObject.filePath);
|
const result = await extractFromArchive(
|
||||||
|
fileObject.filePath
|
||||||
|
);
|
||||||
const {
|
const {
|
||||||
name,
|
name,
|
||||||
filePath,
|
filePath,
|
||||||
@@ -84,7 +108,9 @@ export default class JobQueueService extends Service {
|
|||||||
} = result;
|
} = result;
|
||||||
|
|
||||||
// 3a. Infer any issue-related metadata from the filename
|
// 3a. Infer any issue-related metadata from the filename
|
||||||
const { inferredIssueDetails } = refineQuery(result.name);
|
const { inferredIssueDetails } = refineQuery(
|
||||||
|
result.name
|
||||||
|
);
|
||||||
console.log(
|
console.log(
|
||||||
"Issue metadata inferred: ",
|
"Issue metadata inferred: ",
|
||||||
JSON.stringify(inferredIssueDetails, null, 2)
|
JSON.stringify(inferredIssueDetails, null, 2)
|
||||||
@@ -124,7 +150,8 @@ export default class JobQueueService extends Service {
|
|||||||
// "acquisition.directconnect.downloads": [],
|
// "acquisition.directconnect.downloads": [],
|
||||||
|
|
||||||
// mark the metadata source
|
// mark the metadata source
|
||||||
"acquisition.source.name": ctx.locals.job.data.params.sourcedFrom,
|
"acquisition.source.name":
|
||||||
|
ctx.locals.job.data.params.sourcedFrom,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 3c. Add the bundleId, if present to the payload
|
// 3c. Add the bundleId, if present to the payload
|
||||||
@@ -135,8 +162,13 @@ export default class JobQueueService extends Service {
|
|||||||
|
|
||||||
// 3d. Add the sourcedMetadata, if present
|
// 3d. Add the sourcedMetadata, if present
|
||||||
if (
|
if (
|
||||||
!isNil(ctx.locals.job.data.params.sourcedMetadata) &&
|
!isNil(
|
||||||
!isUndefined(ctx.locals.job.data.params.sourcedMetadata.comicvine)
|
ctx.locals.job.data.params.sourcedMetadata
|
||||||
|
) &&
|
||||||
|
!isUndefined(
|
||||||
|
ctx.locals.job.data.params.sourcedMetadata
|
||||||
|
.comicvine
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
Object.assign(
|
Object.assign(
|
||||||
payload.sourcedMetadata,
|
payload.sourcedMetadata,
|
||||||
@@ -145,11 +177,15 @@ export default class JobQueueService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 4. write to mongo
|
// 4. write to mongo
|
||||||
const importResult = await this.broker.call("library.rawImportToDB", {
|
const importResult = await this.broker.call(
|
||||||
importType: ctx.locals.job.data.params.importType,
|
"library.rawImportToDB",
|
||||||
bundleId,
|
{
|
||||||
payload,
|
importType:
|
||||||
});
|
ctx.locals.job.data.params.importType,
|
||||||
|
bundleId,
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
data: {
|
data: {
|
||||||
importResult,
|
importResult,
|
||||||
@@ -161,9 +197,14 @@ export default class JobQueueService extends Service {
|
|||||||
console.error(
|
console.error(
|
||||||
`An error occurred processing Job ID ${ctx.locals.job.id}`
|
`An error occurred processing Job ID ${ctx.locals.job.id}`
|
||||||
);
|
);
|
||||||
throw new MoleculerError(error, 500, "IMPORT_JOB_ERROR", {
|
throw new MoleculerError(
|
||||||
data: ctx.params.sessionId,
|
error,
|
||||||
});
|
500,
|
||||||
|
"IMPORT_JOB_ERROR",
|
||||||
|
{
|
||||||
|
data: ctx.params.sessionId,
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -191,7 +232,8 @@ export default class JobQueueService extends Service {
|
|||||||
statuses: {
|
statuses: {
|
||||||
$push: {
|
$push: {
|
||||||
status: "$_id.status",
|
status: "$_id.status",
|
||||||
earliestTimestamp: "$earliestTimestamp",
|
earliestTimestamp:
|
||||||
|
"$earliestTimestamp",
|
||||||
count: "$count",
|
count: "$count",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -211,7 +253,10 @@ export default class JobQueueService extends Service {
|
|||||||
{
|
{
|
||||||
$cond: [
|
$cond: [
|
||||||
{
|
{
|
||||||
$eq: ["$$this.status", "completed"],
|
$eq: [
|
||||||
|
"$$this.status",
|
||||||
|
"completed",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
"$$this.count",
|
"$$this.count",
|
||||||
0,
|
0,
|
||||||
@@ -231,7 +276,10 @@ export default class JobQueueService extends Service {
|
|||||||
{
|
{
|
||||||
$cond: [
|
$cond: [
|
||||||
{
|
{
|
||||||
$eq: ["$$this.status", "failed"],
|
$eq: [
|
||||||
|
"$$this.status",
|
||||||
|
"failed",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
"$$this.count",
|
"$$this.count",
|
||||||
0,
|
0,
|
||||||
@@ -249,9 +297,75 @@ export default class JobQueueService extends Service {
|
|||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
"uncompressFullArchive.async": {
|
||||||
|
rest: "POST /uncompressFullArchive",
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
filePath: string;
|
||||||
|
comicObjectId: string;
|
||||||
|
options: any;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
console.log(
|
||||||
|
`Recieved Job ID ${JSON.stringify(
|
||||||
|
ctx.locals
|
||||||
|
)}, processing...`
|
||||||
|
);
|
||||||
|
const { filePath, options, comicObjectId } = ctx.params;
|
||||||
|
const comicId = new ObjectId(comicObjectId);
|
||||||
|
// 2. Extract metadata from the archive
|
||||||
|
const result: string[] = await uncompressEntireArchive(
|
||||||
|
filePath,
|
||||||
|
options
|
||||||
|
);
|
||||||
|
if (Array.isArray(result) && result.length !== 0) {
|
||||||
|
// Get the containing directory of the uncompressed archive
|
||||||
|
const directoryPath = path.dirname(result[0]);
|
||||||
|
// Add to mongo object
|
||||||
|
await Comic.findByIdAndUpdate(
|
||||||
|
comicId,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
"rawFileDetails.archive": {
|
||||||
|
uncompressed: true,
|
||||||
|
expandedPath: directoryPath,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ new: true, safe: true, upsert: true }
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
events: {
|
events: {
|
||||||
|
async "uncompressFullArchive.async.active"(
|
||||||
|
ctx: Context<{ id: number }>
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`Uncompression Job ID ${ctx.params.id} is set to active.`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
async "uncompressFullArchive.async.completed"(
|
||||||
|
ctx: Context<{ id: number }>
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`Uncompression Job ID ${ctx.params.id} completed.`
|
||||||
|
);
|
||||||
|
const job = await this.job(ctx.params.id);
|
||||||
|
await this.broker.call("socket.broadcast", {
|
||||||
|
namespace: "/",
|
||||||
|
event: "LS_UNCOMPRESSION_JOB_COMPLETE",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
uncompressedArchive: job.returnvalue,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
return job.returnvalue;
|
||||||
|
},
|
||||||
// use the `${QUEUE_NAME}.QUEUE_EVENT` scheme
|
// use the `${QUEUE_NAME}.QUEUE_EVENT` scheme
|
||||||
async "enqueue.async.active"(ctx: Context<{ id: Number }>) {
|
async "enqueue.async.active"(ctx: Context<{ id: Number }>) {
|
||||||
console.log(`Job ID ${ctx.params.id} is set to active.`);
|
console.log(`Job ID ${ctx.params.id} is set to active.`);
|
||||||
@@ -260,10 +374,10 @@ export default class JobQueueService extends Service {
|
|||||||
console.log("Queue drained.");
|
console.log("Queue drained.");
|
||||||
await this.broker.call("socket.broadcast", {
|
await this.broker.call("socket.broadcast", {
|
||||||
namespace: "/",
|
namespace: "/",
|
||||||
event: "action",
|
event: "LS_IMPORT_QUEUE_DRAINED",
|
||||||
args: [
|
args: [
|
||||||
{
|
{
|
||||||
type: "LS_IMPORT_QUEUE_DRAINED",
|
message: "drained",
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
@@ -274,14 +388,15 @@ export default class JobQueueService extends Service {
|
|||||||
// 2. Increment the completed job counter
|
// 2. Increment the completed job counter
|
||||||
await pubClient.incr("completedJobCount");
|
await pubClient.incr("completedJobCount");
|
||||||
// 3. Fetch the completed job count for the final payload to be sent to the client
|
// 3. Fetch the completed job count for the final payload to be sent to the client
|
||||||
const completedJobCount = await pubClient.get("completedJobCount");
|
const completedJobCount = await pubClient.get(
|
||||||
|
"completedJobCount"
|
||||||
|
);
|
||||||
// 4. Emit the LS_COVER_EXTRACTED event with the necessary details
|
// 4. Emit the LS_COVER_EXTRACTED event with the necessary details
|
||||||
await this.broker.call("socket.broadcast", {
|
await this.broker.call("socket.broadcast", {
|
||||||
namespace: "/",
|
namespace: "/",
|
||||||
event: "action",
|
event: "LS_COVER_EXTRACTED",
|
||||||
args: [
|
args: [
|
||||||
{
|
{
|
||||||
type: "LS_COVER_EXTRACTED",
|
|
||||||
completedJobCount,
|
completedJobCount,
|
||||||
importResult: job.returnvalue.data.importResult,
|
importResult: job.returnvalue.data.importResult,
|
||||||
},
|
},
|
||||||
@@ -302,7 +417,9 @@ export default class JobQueueService extends Service {
|
|||||||
async "enqueue.async.failed"(ctx) {
|
async "enqueue.async.failed"(ctx) {
|
||||||
const job = await this.job(ctx.params.id);
|
const job = await this.job(ctx.params.id);
|
||||||
await pubClient.incr("failedJobCount");
|
await pubClient.incr("failedJobCount");
|
||||||
const failedJobCount = await pubClient.get("failedJobCount");
|
const failedJobCount = await pubClient.get(
|
||||||
|
"failedJobCount"
|
||||||
|
);
|
||||||
|
|
||||||
await JobResult.create({
|
await JobResult.create({
|
||||||
id: ctx.params.id,
|
id: ctx.params.id,
|
||||||
@@ -315,10 +432,9 @@ export default class JobQueueService extends Service {
|
|||||||
// 4. Emit the LS_COVER_EXTRACTION_FAILED event with the necessary details
|
// 4. Emit the LS_COVER_EXTRACTION_FAILED event with the necessary details
|
||||||
await this.broker.call("socket.broadcast", {
|
await this.broker.call("socket.broadcast", {
|
||||||
namespace: "/",
|
namespace: "/",
|
||||||
event: "action",
|
event: "LS_COVER_EXTRACTION_FAILED",
|
||||||
args: [
|
args: [
|
||||||
{
|
{
|
||||||
type: "LS_COVER_EXTRACTION_FAILED",
|
|
||||||
failedJobCount,
|
failedJobCount,
|
||||||
importResult: job,
|
importResult: job,
|
||||||
},
|
},
|
||||||
@@ -326,6 +442,7 @@ export default class JobQueueService extends Service {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
methods: {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,7 +33,13 @@ SOFTWARE.
|
|||||||
|
|
||||||
"use strict";
|
"use strict";
|
||||||
import { isNil } from "lodash";
|
import { isNil } from "lodash";
|
||||||
import { Context, Service, ServiceBroker, ServiceSchema, Errors } from "moleculer";
|
import {
|
||||||
|
Context,
|
||||||
|
Service,
|
||||||
|
ServiceBroker,
|
||||||
|
ServiceSchema,
|
||||||
|
Errors,
|
||||||
|
} from "moleculer";
|
||||||
import { DbMixin } from "../mixins/db.mixin";
|
import { DbMixin } from "../mixins/db.mixin";
|
||||||
import Comic from "../models/comic.model";
|
import Comic from "../models/comic.model";
|
||||||
import { walkFolder, getSizeOfDirectory } from "../utils/file.utils";
|
import { walkFolder, getSizeOfDirectory } from "../utils/file.utils";
|
||||||
@@ -51,10 +57,13 @@ const through2 = require("through2");
|
|||||||
import klaw from "klaw";
|
import klaw from "klaw";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { COMICS_DIRECTORY, USERDATA_DIRECTORY } from "../constants/directories";
|
import { COMICS_DIRECTORY, USERDATA_DIRECTORY } from "../constants/directories";
|
||||||
|
import AirDCPPSocket from "../shared/airdcpp.socket";
|
||||||
|
|
||||||
console.log(`MONGO -> ${process.env.MONGO_URI}`);
|
export default class LibraryService extends Service {
|
||||||
export default class ImportService extends Service {
|
public constructor(
|
||||||
public constructor(public broker: ServiceBroker) {
|
public broker: ServiceBroker,
|
||||||
|
schema: ServiceSchema<{}> = { name: "library" }
|
||||||
|
) {
|
||||||
super(broker);
|
super(broker);
|
||||||
this.parseServiceSchema({
|
this.parseServiceSchema({
|
||||||
name: "library",
|
name: "library",
|
||||||
@@ -74,14 +83,19 @@ export default class ImportService extends Service {
|
|||||||
},
|
},
|
||||||
walkFolders: {
|
walkFolders: {
|
||||||
rest: "POST /walkFolders",
|
rest: "POST /walkFolders",
|
||||||
params: {
|
params: {},
|
||||||
basePathToWalk: "string",
|
async handler(
|
||||||
},
|
ctx: Context<{
|
||||||
async handler(ctx: Context<{ basePathToWalk: string }>) {
|
basePathToWalk: string;
|
||||||
|
extensions: string[];
|
||||||
|
}>
|
||||||
|
) {
|
||||||
|
console.log(ctx.params);
|
||||||
return await walkFolder(ctx.params.basePathToWalk, [
|
return await walkFolder(ctx.params.basePathToWalk, [
|
||||||
".cbz",
|
".cbz",
|
||||||
".cbr",
|
".cbr",
|
||||||
".cb7",
|
".cb7",
|
||||||
|
...ctx.params.extensions,
|
||||||
]);
|
]);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -95,10 +109,19 @@ export default class ImportService extends Service {
|
|||||||
uncompressFullArchive: {
|
uncompressFullArchive: {
|
||||||
rest: "POST /uncompressFullArchive",
|
rest: "POST /uncompressFullArchive",
|
||||||
params: {},
|
params: {},
|
||||||
handler: async (ctx: Context<{ filePath: string; options: any }>) => {
|
handler: async (
|
||||||
await broker.call("importqueue.uncompressResize", {
|
ctx: Context<{
|
||||||
|
filePath: string;
|
||||||
|
comicObjectId: string;
|
||||||
|
options: any;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
this.broker.call("jobqueue.enqueue", {
|
||||||
filePath: ctx.params.filePath,
|
filePath: ctx.params.filePath,
|
||||||
|
comicObjectId: ctx.params.comicObjectId,
|
||||||
options: ctx.params.options,
|
options: ctx.params.options,
|
||||||
|
action: "uncompressFullArchive.async",
|
||||||
|
description: `Job for uncompressing archive at ${ctx.params.filePath}`,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -113,7 +136,8 @@ export default class ImportService extends Service {
|
|||||||
});
|
});
|
||||||
// Determine source where the comic was added from
|
// Determine source where the comic was added from
|
||||||
// and gather identifying information about it
|
// and gather identifying information about it
|
||||||
const sourceName = referenceComicObject[0].acquisition.source.name;
|
const sourceName =
|
||||||
|
referenceComicObject[0].acquisition.source.name;
|
||||||
const { sourcedMetadata } = referenceComicObject[0];
|
const { sourcedMetadata } = referenceComicObject[0];
|
||||||
|
|
||||||
const filePath = `${COMICS_DIRECTORY}/${ctx.params.bundle.data.name}`;
|
const filePath = `${COMICS_DIRECTORY}/${ctx.params.bundle.data.name}`;
|
||||||
@@ -142,60 +166,52 @@ export default class ImportService extends Service {
|
|||||||
},
|
},
|
||||||
newImport: {
|
newImport: {
|
||||||
rest: "POST /newImport",
|
rest: "POST /newImport",
|
||||||
// params: {},
|
async handler(ctx) {
|
||||||
async handler(
|
const { sessionId } = ctx.params;
|
||||||
ctx: Context<{
|
|
||||||
extractionOptions?: any;
|
|
||||||
sessionId: string;
|
|
||||||
}>
|
|
||||||
) {
|
|
||||||
try {
|
try {
|
||||||
// Get params to be passed to the import jobs
|
// Initialize Redis counters once at the start of the import
|
||||||
const { sessionId } = ctx.params;
|
await pubClient.set("completedJobCount", 0);
|
||||||
// 1. Walk the Source folder
|
await pubClient.set("failedJobCount", 0);
|
||||||
klaw(path.resolve(COMICS_DIRECTORY))
|
|
||||||
// 1.1 Filter on .cb* extensions
|
// Convert klaw to use a promise-based approach for better flow control
|
||||||
.pipe(
|
const files = await this.getComicFiles(
|
||||||
through2.obj(function (item, enc, next) {
|
COMICS_DIRECTORY
|
||||||
let fileExtension = path.extname(item.path);
|
);
|
||||||
if ([".cbz", ".cbr", ".cb7"].includes(fileExtension)) {
|
for (const file of files) {
|
||||||
this.push(item);
|
console.info(
|
||||||
}
|
"Found a file at path:",
|
||||||
next();
|
file.path
|
||||||
})
|
);
|
||||||
)
|
const comicExists = await Comic.exists({
|
||||||
// 1.2 Pipe filtered results to the next step
|
"rawFileDetails.name": path.basename(
|
||||||
// Enqueue the job in the queue
|
file.path,
|
||||||
.on("data", async (item) => {
|
path.extname(file.path)
|
||||||
console.info("Found a file at path: %s", item.path);
|
),
|
||||||
let comicExists = await Comic.exists({
|
|
||||||
"rawFileDetails.name": `${path.basename(
|
|
||||||
item.path,
|
|
||||||
path.extname(item.path)
|
|
||||||
)}`,
|
|
||||||
});
|
|
||||||
if (!comicExists) {
|
|
||||||
// 2.1 Reset the job counters in Redis
|
|
||||||
await pubClient.set("completedJobCount", 0);
|
|
||||||
await pubClient.set("failedJobCount", 0);
|
|
||||||
// 2.2 Send the extraction job to the queue
|
|
||||||
this.broker.call("jobqueue.enqueue", {
|
|
||||||
fileObject: {
|
|
||||||
filePath: item.path,
|
|
||||||
fileSize: item.stats.size,
|
|
||||||
},
|
|
||||||
sessionId,
|
|
||||||
importType: "new",
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.log("Comic already exists in the library.");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.on("end", () => {
|
|
||||||
console.log("All files traversed.");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!comicExists) {
|
||||||
|
// Send the extraction job to the queue
|
||||||
|
await this.broker.call("jobqueue.enqueue", {
|
||||||
|
fileObject: {
|
||||||
|
filePath: file.path,
|
||||||
|
fileSize: file.stats.size,
|
||||||
|
},
|
||||||
|
sessionId,
|
||||||
|
importType: "new",
|
||||||
|
action: "enqueue.async",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log(
|
||||||
|
"Comic already exists in the library."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log("All files traversed.");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.error(
|
||||||
|
"Error during newImport processing:",
|
||||||
|
error
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -209,10 +225,7 @@ export default class ImportService extends Service {
|
|||||||
payload: {
|
payload: {
|
||||||
_id?: string;
|
_id?: string;
|
||||||
sourcedMetadata: {
|
sourcedMetadata: {
|
||||||
comicvine?: {
|
comicvine?: any;
|
||||||
volume: { api_detail_url: string };
|
|
||||||
volumeInformation: {};
|
|
||||||
};
|
|
||||||
locg?: {};
|
locg?: {};
|
||||||
};
|
};
|
||||||
inferredMetadata: {
|
inferredMetadata: {
|
||||||
@@ -221,11 +234,13 @@ export default class ImportService extends Service {
|
|||||||
rawFileDetails: {
|
rawFileDetails: {
|
||||||
name: string;
|
name: string;
|
||||||
};
|
};
|
||||||
|
wanted: {
|
||||||
|
issues: [];
|
||||||
|
volume: { id: number };
|
||||||
|
source: string;
|
||||||
|
markEntireVolumeWanted: Boolean;
|
||||||
|
};
|
||||||
acquisition: {
|
acquisition: {
|
||||||
source: {
|
|
||||||
wanted: boolean;
|
|
||||||
name?: string;
|
|
||||||
};
|
|
||||||
directconnect: {
|
directconnect: {
|
||||||
downloads: [];
|
downloads: [];
|
||||||
};
|
};
|
||||||
@@ -234,49 +249,109 @@ export default class ImportService extends Service {
|
|||||||
}>
|
}>
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
let volumeDetails;
|
console.log(
|
||||||
const comicMetadata = ctx.params.payload;
|
JSON.stringify(ctx.params.payload, null, 4)
|
||||||
// When an issue is added from the search CV feature
|
);
|
||||||
// we solicit volume information and add that to mongo
|
const { payload } = ctx.params;
|
||||||
if (
|
const { wanted } = payload;
|
||||||
comicMetadata.sourcedMetadata.comicvine &&
|
|
||||||
!isNil(comicMetadata.sourcedMetadata.comicvine.volume)
|
|
||||||
) {
|
|
||||||
volumeDetails = await this.broker.call("comicvine.getVolumes", {
|
|
||||||
volumeURI:
|
|
||||||
comicMetadata.sourcedMetadata.comicvine.volume
|
|
||||||
.api_detail_url,
|
|
||||||
});
|
|
||||||
comicMetadata.sourcedMetadata.comicvine.volumeInformation =
|
|
||||||
volumeDetails.results;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log("Saving to Mongo...");
|
console.log("Saving to Mongo...");
|
||||||
console.log(`Import type: [${ctx.params.importType}]`);
|
|
||||||
switch (ctx.params.importType) {
|
if (
|
||||||
case "new":
|
!wanted ||
|
||||||
return await Comic.create(comicMetadata);
|
!wanted.volume ||
|
||||||
case "update":
|
!wanted.volume.id
|
||||||
return await Comic.findOneAndUpdate(
|
) {
|
||||||
{
|
console.log(
|
||||||
"acquisition.directconnect.downloads.bundleId":
|
"No valid identifier for upsert. Attempting to create a new document with minimal data..."
|
||||||
ctx.params.bundleId,
|
);
|
||||||
},
|
const newDocument = new Comic(payload); // Using the entire payload for the new document
|
||||||
comicMetadata,
|
|
||||||
{
|
await newDocument.save();
|
||||||
upsert: true,
|
return {
|
||||||
new: true,
|
success: true,
|
||||||
}
|
message:
|
||||||
);
|
"New document created due to lack of valid identifiers.",
|
||||||
default:
|
data: newDocument,
|
||||||
return false;
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let condition = {
|
||||||
|
"wanted.volume.id": wanted.volume.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
let update: any = {
|
||||||
|
// Using 'any' to bypass strict type checks; alternatively, define a more accurate type
|
||||||
|
$set: {
|
||||||
|
rawFileDetails: payload.rawFileDetails,
|
||||||
|
inferredMetadata: payload.inferredMetadata,
|
||||||
|
sourcedMetadata: payload.sourcedMetadata,
|
||||||
|
},
|
||||||
|
$setOnInsert: {
|
||||||
|
"wanted.source": payload.wanted.source,
|
||||||
|
"wanted.markEntireVolumeWanted":
|
||||||
|
payload.wanted.markEntireVolumeWanted,
|
||||||
|
"wanted.volume": payload.wanted.volume,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (wanted.issues && wanted.issues.length > 0) {
|
||||||
|
update.$addToSet = {
|
||||||
|
"wanted.issues": { $each: wanted.issues },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const options = {
|
||||||
|
upsert: true,
|
||||||
|
new: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await Comic.findOneAndUpdate(
|
||||||
|
condition,
|
||||||
|
update,
|
||||||
|
options
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
"Operation completed. Document updated or inserted:",
|
||||||
|
result
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: "Document successfully upserted.",
|
||||||
|
data: result,
|
||||||
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error);
|
console.log(error);
|
||||||
throw new Errors.MoleculerError("Import failed.", 500);
|
throw new Errors.MoleculerError(
|
||||||
|
"Operation failed.",
|
||||||
|
500
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
getComicsMarkedAsWanted: {
|
||||||
|
rest: "GET /getComicsMarkedAsWanted",
|
||||||
|
handler: async (ctx: Context<{}>) => {
|
||||||
|
try {
|
||||||
|
// Query to find comics where 'markEntireVolumeAsWanted' is true or 'issues' array is not empty
|
||||||
|
const wantedComics = await Comic.find({
|
||||||
|
wanted: { $exists: true },
|
||||||
|
$or: [
|
||||||
|
{ "wanted.markEntireVolumeWanted": true },
|
||||||
|
{ "wanted.issues": { $not: { $size: 0 } } },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(wantedComics); // Output the found comics
|
||||||
|
return wantedComics;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error finding comics:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
applyComicVineMetadata: {
|
applyComicVineMetadata: {
|
||||||
rest: "POST /applyComicVineMetadata",
|
rest: "POST /applyComicVineMetadata",
|
||||||
params: {},
|
params: {},
|
||||||
@@ -291,7 +366,9 @@ export default class ImportService extends Service {
|
|||||||
) {
|
) {
|
||||||
// 1. Find mongo object by id
|
// 1. Find mongo object by id
|
||||||
// 2. Import payload into sourcedMetadata.comicvine
|
// 2. Import payload into sourcedMetadata.comicvine
|
||||||
const comicObjectId = new ObjectId(ctx.params.comicObjectId);
|
const comicObjectId = new ObjectId(
|
||||||
|
ctx.params.comicObjectId
|
||||||
|
);
|
||||||
|
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
let volumeDetails = {};
|
let volumeDetails = {};
|
||||||
@@ -300,15 +377,18 @@ export default class ImportService extends Service {
|
|||||||
const volumeDetails = await this.broker.call(
|
const volumeDetails = await this.broker.call(
|
||||||
"comicvine.getVolumes",
|
"comicvine.getVolumes",
|
||||||
{
|
{
|
||||||
volumeURI: matchedResult.volume.api_detail_url,
|
volumeURI:
|
||||||
|
matchedResult.volume.api_detail_url,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
matchedResult.volumeInformation = volumeDetails.results;
|
matchedResult.volumeInformation =
|
||||||
|
volumeDetails.results;
|
||||||
Comic.findByIdAndUpdate(
|
Comic.findByIdAndUpdate(
|
||||||
comicObjectId,
|
comicObjectId,
|
||||||
{
|
{
|
||||||
$set: {
|
$set: {
|
||||||
"sourcedMetadata.comicvine": matchedResult,
|
"sourcedMetadata.comicvine":
|
||||||
|
matchedResult,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ new: true },
|
{ new: true },
|
||||||
@@ -339,7 +419,9 @@ export default class ImportService extends Service {
|
|||||||
}>
|
}>
|
||||||
) {
|
) {
|
||||||
console.log(JSON.stringify(ctx.params, null, 2));
|
console.log(JSON.stringify(ctx.params, null, 2));
|
||||||
const comicObjectId = new ObjectId(ctx.params.comicObjectId);
|
const comicObjectId = new ObjectId(
|
||||||
|
ctx.params.comicObjectId
|
||||||
|
);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
Comic.findByIdAndUpdate(
|
Comic.findByIdAndUpdate(
|
||||||
@@ -366,6 +448,66 @@ export default class ImportService extends Service {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
applyTorrentDownloadMetadata: {
|
||||||
|
rest: "POST /applyTorrentDownloadMetadata",
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
torrentToDownload: any;
|
||||||
|
comicObjectId: String;
|
||||||
|
infoHash: String;
|
||||||
|
name: String;
|
||||||
|
announce: [String];
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
const {
|
||||||
|
name,
|
||||||
|
torrentToDownload,
|
||||||
|
comicObjectId,
|
||||||
|
announce,
|
||||||
|
infoHash,
|
||||||
|
} = ctx.params;
|
||||||
|
console.log(JSON.stringify(ctx.params, null, 4));
|
||||||
|
try {
|
||||||
|
return await Comic.findByIdAndUpdate(
|
||||||
|
new ObjectId(comicObjectId),
|
||||||
|
{
|
||||||
|
$push: {
|
||||||
|
"acquisition.torrent": {
|
||||||
|
infoHash,
|
||||||
|
name,
|
||||||
|
announce,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ new: true, safe: true, upsert: true }
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.log(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
getInfoHashes: {
|
||||||
|
rest: "GET /getInfoHashes",
|
||||||
|
handler: async (ctx: Context<{}>) => {
|
||||||
|
try {
|
||||||
|
return await Comic.aggregate([
|
||||||
|
{
|
||||||
|
$unwind: "$acquisition.torrent",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: "$_id",
|
||||||
|
infoHashes: {
|
||||||
|
$push: "$acquisition.torrent.infoHash",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
} catch (err) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
getComicBooks: {
|
getComicBooks: {
|
||||||
rest: "POST /getComicBooks",
|
rest: "POST /getComicBooks",
|
||||||
params: {},
|
params: {},
|
||||||
@@ -385,7 +527,10 @@ export default class ImportService extends Service {
|
|||||||
rest: "POST /getComicBookById",
|
rest: "POST /getComicBookById",
|
||||||
params: { id: "string" },
|
params: { id: "string" },
|
||||||
async handler(ctx: Context<{ id: string }>) {
|
async handler(ctx: Context<{ id: string }>) {
|
||||||
return await Comic.findById(ctx.params.id);
|
console.log(ctx.params.id);
|
||||||
|
return await Comic.findById(
|
||||||
|
new ObjectId(ctx.params.id)
|
||||||
|
);
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
getComicBooksByIds: {
|
getComicBooksByIds: {
|
||||||
@@ -393,7 +538,9 @@ export default class ImportService extends Service {
|
|||||||
params: { ids: "array" },
|
params: { ids: "array" },
|
||||||
handler: async (ctx: Context<{ ids: [string] }>) => {
|
handler: async (ctx: Context<{ ids: [string] }>) => {
|
||||||
console.log(ctx.params.ids);
|
console.log(ctx.params.ids);
|
||||||
const queryIds = ctx.params.ids.map((id) => new ObjectId(id));
|
const queryIds = ctx.params.ids.map(
|
||||||
|
(id) => new ObjectId(id)
|
||||||
|
);
|
||||||
return await Comic.find({
|
return await Comic.find({
|
||||||
_id: {
|
_id: {
|
||||||
$in: queryIds,
|
$in: queryIds,
|
||||||
@@ -409,7 +556,8 @@ export default class ImportService extends Service {
|
|||||||
const volumes = await Comic.aggregate([
|
const volumes = await Comic.aggregate([
|
||||||
{
|
{
|
||||||
$project: {
|
$project: {
|
||||||
volumeInfo: "$sourcedMetadata.comicvine.volumeInformation",
|
volumeInfo:
|
||||||
|
"$sourcedMetadata.comicvine.volumeInformation",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -455,46 +603,52 @@ export default class ImportService extends Service {
|
|||||||
const { queryObjects } = ctx.params;
|
const { queryObjects } = ctx.params;
|
||||||
// construct the query for ElasticSearch
|
// construct the query for ElasticSearch
|
||||||
let elasticSearchQuery = {};
|
let elasticSearchQuery = {};
|
||||||
const elasticSearchQueries = queryObjects.map((queryObject) => {
|
const elasticSearchQueries = queryObjects.map(
|
||||||
console.log("Volume: ", queryObject.volumeName);
|
(queryObject) => {
|
||||||
console.log("Issue: ", queryObject.issueName);
|
console.log("Volume: ", queryObject.volumeName);
|
||||||
if (queryObject.issueName === null) {
|
console.log("Issue: ", queryObject.issueName);
|
||||||
queryObject.issueName = "";
|
if (queryObject.issueName === null) {
|
||||||
}
|
queryObject.issueName = "";
|
||||||
if (queryObject.volumeName === null) {
|
}
|
||||||
queryObject.volumeName = "";
|
if (queryObject.volumeName === null) {
|
||||||
}
|
queryObject.volumeName = "";
|
||||||
elasticSearchQuery = {
|
}
|
||||||
bool: {
|
elasticSearchQuery = {
|
||||||
must: [
|
bool: {
|
||||||
{
|
must: [
|
||||||
match_phrase: {
|
{
|
||||||
"rawFileDetails.name": queryObject.volumeName,
|
match_phrase: {
|
||||||
|
"rawFileDetails.name":
|
||||||
|
queryObject.volumeName,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
{
|
term: {
|
||||||
term: {
|
"inferredMetadata.issue.number":
|
||||||
"inferredMetadata.issue.number": parseInt(
|
parseInt(
|
||||||
queryObject.issueNumber,
|
queryObject.issueNumber,
|
||||||
10
|
10
|
||||||
),
|
),
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
],
|
||||||
],
|
},
|
||||||
},
|
};
|
||||||
};
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
index: "comics",
|
index: "comics",
|
||||||
search_type: "dfs_query_then_fetch",
|
search_type: "dfs_query_then_fetch",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
query: elasticSearchQuery,
|
query: elasticSearchQuery,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
});
|
}
|
||||||
console.log(JSON.stringify(elasticSearchQueries, null, 2));
|
);
|
||||||
|
console.log(
|
||||||
|
JSON.stringify(elasticSearchQueries, null, 2)
|
||||||
|
);
|
||||||
|
|
||||||
return await ctx.broker.call("search.searchComic", {
|
return await ctx.broker.call("search.searchComic", {
|
||||||
elasticSearchQueries,
|
elasticSearchQueries,
|
||||||
@@ -507,11 +661,10 @@ export default class ImportService extends Service {
|
|||||||
rest: "GET /libraryStatistics",
|
rest: "GET /libraryStatistics",
|
||||||
params: {},
|
params: {},
|
||||||
handler: async (ctx: Context<{}>) => {
|
handler: async (ctx: Context<{}>) => {
|
||||||
const comicDirectorySize = await getSizeOfDirectory(COMICS_DIRECTORY, [
|
const comicDirectorySize = await getSizeOfDirectory(
|
||||||
".cbz",
|
COMICS_DIRECTORY,
|
||||||
".cbr",
|
[".cbz", ".cbr", ".cb7"]
|
||||||
".cb7",
|
);
|
||||||
]);
|
|
||||||
const totalCount = await Comic.countDocuments({});
|
const totalCount = await Comic.countDocuments({});
|
||||||
const statistics = await Comic.aggregate([
|
const statistics = await Comic.aggregate([
|
||||||
{
|
{
|
||||||
@@ -520,7 +673,11 @@ export default class ImportService extends Service {
|
|||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
"rawFileDetails.extension": {
|
"rawFileDetails.extension": {
|
||||||
$in: [".cbr", ".cbz", ".cb7"],
|
$in: [
|
||||||
|
".cbr",
|
||||||
|
".cbz",
|
||||||
|
".cb7",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -534,9 +691,10 @@ export default class ImportService extends Service {
|
|||||||
issues: [
|
issues: [
|
||||||
{
|
{
|
||||||
$match: {
|
$match: {
|
||||||
"sourcedMetadata.comicvine.volumeInformation": {
|
"sourcedMetadata.comicvine.volumeInformation":
|
||||||
$gt: {},
|
{
|
||||||
},
|
$gt: {},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -591,6 +749,48 @@ export default class ImportService extends Service {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// This method belongs in library service,
|
||||||
|
// because bundles can only exist for comics _in the library_
|
||||||
|
// (wanted or imported)
|
||||||
|
getBundles: {
|
||||||
|
rest: "POST /getBundles",
|
||||||
|
params: {},
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
comicObjectId: string;
|
||||||
|
config: any;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
// 1. Get the comic object Id
|
||||||
|
const { config } = ctx.params;
|
||||||
|
const comicObject = await Comic.findById(
|
||||||
|
new ObjectId(ctx.params.comicObjectId)
|
||||||
|
);
|
||||||
|
// 2. Init AirDC++
|
||||||
|
const ADCPPSocket = new AirDCPPSocket(config);
|
||||||
|
await ADCPPSocket.connect();
|
||||||
|
// 3. Get the bundles for the comic object
|
||||||
|
if (comicObject) {
|
||||||
|
// make the call to get the bundles from AirDC++ using the bundleId
|
||||||
|
const bundles =
|
||||||
|
comicObject.acquisition.directconnect.downloads.map(
|
||||||
|
async (bundle) => {
|
||||||
|
return await ADCPPSocket.get(
|
||||||
|
`queue/bundles/${bundle.bundleId}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return Promise.all(bundles);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Errors.MoleculerError(
|
||||||
|
"Couldn't fetch bundles from AirDC++",
|
||||||
|
500
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
flushDB: {
|
flushDB: {
|
||||||
rest: "POST /flushDB",
|
rest: "POST /flushDB",
|
||||||
params: {},
|
params: {},
|
||||||
@@ -599,16 +799,23 @@ export default class ImportService extends Service {
|
|||||||
.drop()
|
.drop()
|
||||||
.then(async (data) => {
|
.then(async (data) => {
|
||||||
console.info(data);
|
console.info(data);
|
||||||
const coversFolderDeleteResult = fsExtra.emptyDirSync(
|
const coversFolderDeleteResult =
|
||||||
path.resolve(`${USERDATA_DIRECTORY}/covers`)
|
fsExtra.emptyDirSync(
|
||||||
);
|
path.resolve(
|
||||||
const expandedFolderDeleteResult = fsExtra.emptyDirSync(
|
`${USERDATA_DIRECTORY}/covers`
|
||||||
path.resolve(`${USERDATA_DIRECTORY}/expanded`)
|
)
|
||||||
);
|
);
|
||||||
const eSIndicesDeleteResult = await ctx.broker.call(
|
const expandedFolderDeleteResult =
|
||||||
"search.deleteElasticSearchIndices",
|
fsExtra.emptyDirSync(
|
||||||
{}
|
path.resolve(
|
||||||
);
|
`${USERDATA_DIRECTORY}/expanded`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
const eSIndicesDeleteResult =
|
||||||
|
await ctx.broker.call(
|
||||||
|
"search.deleteElasticSearchIndices",
|
||||||
|
{}
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
data,
|
data,
|
||||||
coversFolderDeleteResult,
|
coversFolderDeleteResult,
|
||||||
@@ -633,7 +840,35 @@ export default class ImportService extends Service {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
methods: {},
|
methods: {
|
||||||
|
// Method to walk the directory and filter comic files
|
||||||
|
getComicFiles: (directory) => {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const files = [];
|
||||||
|
klaw(directory)
|
||||||
|
.pipe(
|
||||||
|
through2.obj(function (item, enc, next) {
|
||||||
|
const fileExtension = path.extname(
|
||||||
|
item.path
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
[".cbz", ".cbr", ".cb7"].includes(
|
||||||
|
fileExtension
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
this.push(item);
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.on("data", (item) => {
|
||||||
|
files.push(item);
|
||||||
|
})
|
||||||
|
.on("end", () => resolve(files))
|
||||||
|
.on("error", (err) => reject(err));
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,9 +75,9 @@ export default class SettingsService extends Service {
|
|||||||
) => {
|
) => {
|
||||||
try {
|
try {
|
||||||
console.log(ctx.params);
|
console.log(ctx.params);
|
||||||
const { query, pagination } = ctx.params;
|
const { query, pagination, type } = ctx.params;
|
||||||
let eSQuery = {};
|
let eSQuery = {};
|
||||||
switch (ctx.params.type) {
|
switch (type) {
|
||||||
case "all":
|
case "all":
|
||||||
Object.assign(eSQuery, {
|
Object.assign(eSQuery, {
|
||||||
match_all: {},
|
match_all: {},
|
||||||
@@ -100,12 +100,19 @@ export default class SettingsService extends Service {
|
|||||||
case "wanted":
|
case "wanted":
|
||||||
Object.assign(eSQuery, {
|
Object.assign(eSQuery, {
|
||||||
bool: {
|
bool: {
|
||||||
must: {
|
should: [
|
||||||
term: {
|
{
|
||||||
"acquisition.source.wanted":
|
exists: {
|
||||||
true,
|
field: "wanted.issues",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
{
|
||||||
|
exists: {
|
||||||
|
field: "wanted.volume",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
minimum_should_match: 1,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
} from "moleculer";
|
} from "moleculer";
|
||||||
import { DbMixin } from "../mixins/db.mixin";
|
import { DbMixin } from "../mixins/db.mixin";
|
||||||
import Settings from "../models/settings.model";
|
import Settings from "../models/settings.model";
|
||||||
import { isEmpty, pickBy, identity, map } from "lodash";
|
import { isEmpty, pickBy, identity, map, isNil } from "lodash";
|
||||||
const ObjectId = require("mongoose").Types.ObjectId;
|
const ObjectId = require("mongoose").Types.ObjectId;
|
||||||
|
|
||||||
export default class SettingsService extends Service {
|
export default class SettingsService extends Service {
|
||||||
@@ -28,12 +28,31 @@ export default class SettingsService extends Service {
|
|||||||
rest: "GET /getAllSettings",
|
rest: "GET /getAllSettings",
|
||||||
params: {},
|
params: {},
|
||||||
async handler(ctx: Context<{ settingsKey: string }>) {
|
async handler(ctx: Context<{ settingsKey: string }>) {
|
||||||
const settings = await Settings.find({});
|
const { settingsKey } = ctx.params;
|
||||||
if (isEmpty(settings)) {
|
|
||||||
|
// Initialize a projection object. Include everything by default.
|
||||||
|
let projection = settingsKey
|
||||||
|
? { _id: 0, [settingsKey]: 1 }
|
||||||
|
: {};
|
||||||
|
|
||||||
|
// Find the settings with the dynamic projection
|
||||||
|
const settings = await Settings.find({}, projection);
|
||||||
|
|
||||||
|
if (settings.length === 0) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
console.log(settings[0]);
|
|
||||||
return settings[0];
|
// If settingsKey is provided, return the specific part of the settings.
|
||||||
|
// Otherwise, return the entire settings document.
|
||||||
|
if (settingsKey) {
|
||||||
|
// Check if the specific key exists in the settings document.
|
||||||
|
// Since `settings` is an array, we access the first element.
|
||||||
|
// Then, we use the settingsKey to return only that part of the document.
|
||||||
|
return settings[0][settingsKey] || {};
|
||||||
|
} else {
|
||||||
|
// Return the entire settings document
|
||||||
|
return settings[0];
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -42,44 +61,107 @@ export default class SettingsService extends Service {
|
|||||||
params: {},
|
params: {},
|
||||||
async handler(
|
async handler(
|
||||||
ctx: Context<{
|
ctx: Context<{
|
||||||
settingsPayload: {
|
settingsPayload?: {
|
||||||
host: object;
|
protocol: string;
|
||||||
airDCPPUserSettings: object;
|
hostname: string;
|
||||||
hubs: [];
|
port: string;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
_id?: string;
|
||||||
|
airDCPPUserSettings?: object;
|
||||||
|
hubs?: [];
|
||||||
};
|
};
|
||||||
settingsObjectId: string;
|
settingsObjectId?: string;
|
||||||
|
settingsKey: string;
|
||||||
}>
|
}>
|
||||||
) {
|
) {
|
||||||
console.log("varan bhat", ctx.params);
|
try {
|
||||||
const { host, airDCPPUserSettings, hubs } =
|
console.log(ctx.params);
|
||||||
ctx.params.settingsPayload;
|
let query = {};
|
||||||
let query = {
|
const { settingsKey, settingsObjectId } =
|
||||||
host,
|
ctx.params;
|
||||||
airDCPPUserSettings,
|
const {
|
||||||
hubs,
|
hostname,
|
||||||
};
|
protocol,
|
||||||
const keysToUpdate = pickBy(query, identity);
|
port,
|
||||||
let updateQuery = {};
|
username,
|
||||||
|
password,
|
||||||
|
} = ctx.params.settingsPayload;
|
||||||
|
const host = {
|
||||||
|
hostname,
|
||||||
|
protocol,
|
||||||
|
port,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
};
|
||||||
|
const undefinedPropsInHostname = Object.values(
|
||||||
|
host
|
||||||
|
).filter((value) => value === undefined);
|
||||||
|
|
||||||
map(Object.keys(keysToUpdate), (key) => {
|
// Update, depending what key was passed in params
|
||||||
updateQuery[`directConnect.client.${key}`] =
|
// 1. Construct the update query
|
||||||
query[key];
|
switch (settingsKey) {
|
||||||
});
|
case "bittorrent":
|
||||||
const options = {
|
console.log(
|
||||||
upsert: true,
|
`Recieved settings for ${settingsKey}, building query...`
|
||||||
new: true,
|
);
|
||||||
setDefaultsOnInsert: true,
|
query = {
|
||||||
};
|
...(undefinedPropsInHostname.length ===
|
||||||
const filter = {
|
0 && {
|
||||||
_id: new ObjectId(ctx.params.settingsObjectId),
|
$set: {
|
||||||
};
|
"bittorrent.client.host": host,
|
||||||
const result = Settings.findOneAndUpdate(
|
},
|
||||||
filter,
|
}),
|
||||||
{ $set: updateQuery },
|
};
|
||||||
options
|
break;
|
||||||
);
|
case "directConnect":
|
||||||
|
console.log(
|
||||||
|
`Recieved settings for ${settingsKey}, building query...`
|
||||||
|
);
|
||||||
|
const { hubs, airDCPPUserSettings } =
|
||||||
|
ctx.params.settingsPayload;
|
||||||
|
query = {
|
||||||
|
...(undefinedPropsInHostname.length ===
|
||||||
|
0 && {
|
||||||
|
$set: {
|
||||||
|
"directConnect.client.host":
|
||||||
|
host,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
...(!isNil(hubs) && {
|
||||||
|
$set: {
|
||||||
|
"directConnect.client.hubs":
|
||||||
|
hubs,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
console.log(JSON.stringify(query, null, 4));
|
||||||
|
break;
|
||||||
|
|
||||||
return result;
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Set up options, filters
|
||||||
|
const options = {
|
||||||
|
upsert: true,
|
||||||
|
setDefaultsOnInsert: true,
|
||||||
|
returnDocument: "after",
|
||||||
|
};
|
||||||
|
const filter = settingsObjectId
|
||||||
|
? { _id: settingsObjectId }
|
||||||
|
: {};
|
||||||
|
|
||||||
|
// 3. Execute the mongo query
|
||||||
|
const result = await Settings.findOneAndUpdate(
|
||||||
|
filter,
|
||||||
|
query,
|
||||||
|
options
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
deleteSettings: {
|
deleteSettings: {
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
import { Service, ServiceBroker, ServiceSchema, Context } from "moleculer";
|
import { Service, ServiceBroker, ServiceSchema, Context } from "moleculer";
|
||||||
import { JobType } from "moleculer-bullmq";
|
import { JobType } from "moleculer-bullmq";
|
||||||
import { createClient } from "redis";
|
|
||||||
import { createAdapter } from "@socket.io/redis-adapter";
|
import { createAdapter } from "@socket.io/redis-adapter";
|
||||||
import Session from "../models/session.model";
|
import Session from "../models/session.model";
|
||||||
import { pubClient, subClient } from "../config/redis.config";
|
import { pubClient, subClient } from "../config/redis.config";
|
||||||
const { MoleculerError } = require("moleculer").Errors;
|
const { MoleculerError } = require("moleculer").Errors;
|
||||||
const SocketIOService = require("moleculer-io");
|
const SocketIOService = require("moleculer-io");
|
||||||
const { v4: uuidv4 } = require("uuid");
|
const { v4: uuidv4 } = require("uuid");
|
||||||
|
import AirDCPPSocket from "../shared/airdcpp.socket";
|
||||||
|
|
||||||
export default class SocketService extends Service {
|
export default class SocketService extends Service {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -23,92 +23,12 @@ export default class SocketService extends Service {
|
|||||||
port: process.env.PORT || 3001,
|
port: process.env.PORT || 3001,
|
||||||
io: {
|
io: {
|
||||||
namespaces: {
|
namespaces: {
|
||||||
"/": {
|
"/automated": {
|
||||||
events: {
|
events: {
|
||||||
call: {
|
call: {
|
||||||
// whitelist: ["math.*", "say.*", "accounts.*", "rooms.*", "io.*"],
|
whitelist: [
|
||||||
},
|
"socket.*", // Allow 'search' in the automated namespace
|
||||||
action: async (data) => {
|
],
|
||||||
switch (data.type) {
|
|
||||||
case "RESUME_SESSION":
|
|
||||||
console.log("Attempting to resume session...");
|
|
||||||
try {
|
|
||||||
const sessionRecord = await Session.find({
|
|
||||||
sessionId: data.session.sessionId,
|
|
||||||
});
|
|
||||||
// 1. Check for sessionId's existence, and a match
|
|
||||||
if (
|
|
||||||
sessionRecord.length !== 0 &&
|
|
||||||
sessionRecord[0].sessionId ===
|
|
||||||
data.session.sessionId
|
|
||||||
) {
|
|
||||||
// 2. Find if the queue has active jobs
|
|
||||||
const jobs: JobType = await this.broker.call(
|
|
||||||
"jobqueue.getJobCountsByType",
|
|
||||||
{}
|
|
||||||
);
|
|
||||||
const { active } = jobs;
|
|
||||||
|
|
||||||
if (active > 0) {
|
|
||||||
// 3. Get job counts
|
|
||||||
const completedJobCount =
|
|
||||||
await pubClient.get(
|
|
||||||
"completedJobCount"
|
|
||||||
);
|
|
||||||
const failedJobCount = await pubClient.get(
|
|
||||||
"failedJobCount"
|
|
||||||
);
|
|
||||||
|
|
||||||
// 4. Send the counts to the active socket.io session
|
|
||||||
await this.broker.call("socket.broadcast", {
|
|
||||||
namespace: "/",
|
|
||||||
event: "action",
|
|
||||||
args: [
|
|
||||||
{
|
|
||||||
type: "RESTORE_JOB_COUNTS_AFTER_SESSION_RESTORATION",
|
|
||||||
completedJobCount,
|
|
||||||
failedJobCount,
|
|
||||||
queueStatus: "running",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
throw new MoleculerError(
|
|
||||||
err,
|
|
||||||
500,
|
|
||||||
"SESSION_ID_NOT_FOUND",
|
|
||||||
{
|
|
||||||
data: data.session.sessionId,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "LS_SET_QUEUE_STATUS":
|
|
||||||
console.log(data);
|
|
||||||
await this.broker.call(
|
|
||||||
"jobqueue.toggle",
|
|
||||||
{ action: data.data.queueAction },
|
|
||||||
{}
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
case "LS_SINGLE_IMPORT":
|
|
||||||
console.info("AirDC++ finished a download -> ");
|
|
||||||
console.log(data);
|
|
||||||
await this.broker.call(
|
|
||||||
"library.importDownloadedComic",
|
|
||||||
{ bundle: data },
|
|
||||||
{}
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
// uncompress archive events
|
|
||||||
case "COMICBOOK_EXTRACTION_SUCCESS":
|
|
||||||
console.log(data);
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -119,9 +39,256 @@ export default class SocketService extends Service {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
hooks: {},
|
hooks: {},
|
||||||
actions: {},
|
actions: {
|
||||||
methods: {},
|
resumeSession: async (ctx: Context<{ sessionId: string }>) => {
|
||||||
|
const { sessionId } = ctx.params;
|
||||||
|
console.log("Attempting to resume session...");
|
||||||
|
try {
|
||||||
|
const sessionRecord = await Session.find({
|
||||||
|
sessionId,
|
||||||
|
});
|
||||||
|
// 1. Check for sessionId's existence, and a match
|
||||||
|
if (
|
||||||
|
sessionRecord.length !== 0 &&
|
||||||
|
sessionRecord[0].sessionId === sessionId
|
||||||
|
) {
|
||||||
|
// 2. Find if the queue has active, paused or waiting jobs
|
||||||
|
const jobs: JobType = await this.broker.call(
|
||||||
|
"jobqueue.getJobCountsByType",
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
const { active, paused, waiting } = jobs;
|
||||||
|
|
||||||
|
if (active > 0 || paused > 0 || waiting > 0) {
|
||||||
|
// 3. Get job counts
|
||||||
|
const completedJobCount = await pubClient.get("completedJobCount");
|
||||||
|
const failedJobCount = await pubClient.get("failedJobCount");
|
||||||
|
|
||||||
|
// 4. Send the counts to the active socket.io session
|
||||||
|
await this.broker.call("socket.broadcast", {
|
||||||
|
namespace: "/",
|
||||||
|
event: "RESTORE_JOB_COUNTS_AFTER_SESSION_RESTORATION",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
completedJobCount,
|
||||||
|
failedJobCount,
|
||||||
|
queueStatus: "running",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
throw new MoleculerError(err, 500, "SESSION_ID_NOT_FOUND", {
|
||||||
|
data: sessionId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
setQueueStatus: async (
|
||||||
|
ctx: Context<{
|
||||||
|
queueAction: string;
|
||||||
|
queueStatus: string;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
const { queueAction } = ctx.params;
|
||||||
|
await this.broker.call("jobqueue.toggle", { action: queueAction }, {});
|
||||||
|
},
|
||||||
|
importSingleIssue: async (ctx: Context<{}>) => {
|
||||||
|
console.info("AirDC++ finished a download -> ");
|
||||||
|
console.log(ctx.params);
|
||||||
|
// await this.broker.call(
|
||||||
|
// "library.importDownloadedComic",
|
||||||
|
// { bundle: data },
|
||||||
|
// {}
|
||||||
|
// );
|
||||||
|
},
|
||||||
|
|
||||||
|
search: {
|
||||||
|
params: {
|
||||||
|
query: "object",
|
||||||
|
config: "object",
|
||||||
|
},
|
||||||
|
async handler(ctx) {
|
||||||
|
const { query, config, namespace } = ctx.params;
|
||||||
|
const namespacedInstance = this.io.of(namespace || "/");
|
||||||
|
const ADCPPSocket = new AirDCPPSocket(config);
|
||||||
|
try {
|
||||||
|
await ADCPPSocket.connect();
|
||||||
|
const instance = await ADCPPSocket.post("search", query);
|
||||||
|
|
||||||
|
// Send the instance to the client
|
||||||
|
await namespacedInstance.emit("searchInitiated", {
|
||||||
|
instance,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Setting up listeners
|
||||||
|
await ADCPPSocket.addListener(
|
||||||
|
`search`,
|
||||||
|
`search_result_added`,
|
||||||
|
(groupedResult) => {
|
||||||
|
console.log(JSON.stringify(groupedResult, null, 4));
|
||||||
|
namespacedInstance.emit("searchResultAdded", groupedResult);
|
||||||
|
},
|
||||||
|
instance.id
|
||||||
|
);
|
||||||
|
|
||||||
|
await ADCPPSocket.addListener(
|
||||||
|
`search`,
|
||||||
|
`search_result_updated`,
|
||||||
|
(updatedResult) => {
|
||||||
|
namespacedInstance.emit("searchResultUpdated", updatedResult);
|
||||||
|
},
|
||||||
|
instance.id
|
||||||
|
);
|
||||||
|
|
||||||
|
await ADCPPSocket.addListener(
|
||||||
|
`search`,
|
||||||
|
`search_hub_searches_sent`,
|
||||||
|
async (searchInfo) => {
|
||||||
|
await this.sleep(5000);
|
||||||
|
const currentInstance = await ADCPPSocket.get(
|
||||||
|
`search/${instance.id}`
|
||||||
|
);
|
||||||
|
// Send the instance to the client
|
||||||
|
await namespacedInstance.emit("searchesSent", {
|
||||||
|
searchInfo,
|
||||||
|
});
|
||||||
|
if (currentInstance.result_count === 0) {
|
||||||
|
console.log("No more search results.");
|
||||||
|
namespacedInstance.emit("searchComplete", {
|
||||||
|
message: "No more search results.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
instance.id
|
||||||
|
);
|
||||||
|
|
||||||
|
// Perform the actual search
|
||||||
|
await ADCPPSocket.post(`search/${instance.id}/hub_search`, query);
|
||||||
|
} catch (error) {
|
||||||
|
await namespacedInstance.emit("searchError", error.message);
|
||||||
|
throw new MoleculerError("Search failed", 500, "SEARCH_FAILED", {
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// await ADCPPSocket.disconnect();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
download: {
|
||||||
|
// params: {
|
||||||
|
// searchInstanceId: "string",
|
||||||
|
// resultId: "string",
|
||||||
|
// comicObjectId: "string",
|
||||||
|
// name: "string",
|
||||||
|
// size: "number",
|
||||||
|
// type: "any", // Define more specific type if possible
|
||||||
|
// config: "object",
|
||||||
|
// },
|
||||||
|
async handler(ctx) {
|
||||||
|
console.log(ctx.params);
|
||||||
|
const {
|
||||||
|
searchInstanceId,
|
||||||
|
resultId,
|
||||||
|
config,
|
||||||
|
comicObjectId,
|
||||||
|
name,
|
||||||
|
size,
|
||||||
|
type,
|
||||||
|
} = ctx.params;
|
||||||
|
const ADCPPSocket = new AirDCPPSocket(config);
|
||||||
|
try {
|
||||||
|
await ADCPPSocket.connect();
|
||||||
|
const downloadResult = await ADCPPSocket.post(
|
||||||
|
`search/${searchInstanceId}/results/${resultId}/download`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (downloadResult && downloadResult.bundle_info) {
|
||||||
|
// Assume bundle_info is part of the response and contains the necessary details
|
||||||
|
const bundleDBImportResult = await ctx.call(
|
||||||
|
"library.applyAirDCPPDownloadMetadata",
|
||||||
|
{
|
||||||
|
bundleId: downloadResult.bundle_info.id,
|
||||||
|
comicObjectId,
|
||||||
|
name,
|
||||||
|
size,
|
||||||
|
type,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
this.logger.info(
|
||||||
|
"Download and metadata update successful",
|
||||||
|
bundleDBImportResult
|
||||||
|
);
|
||||||
|
this.broker.emit("downloadCompleted", bundleDBImportResult);
|
||||||
|
return bundleDBImportResult;
|
||||||
|
} else {
|
||||||
|
throw new Error(
|
||||||
|
"Failed to download or missing download result information"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.broker.emit("downloadError", error.message);
|
||||||
|
throw new MoleculerError("Download failed", 500, "DOWNLOAD_FAILED", {
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// await ADCPPSocket.disconnect();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
listenBundleTick: {
|
||||||
|
async handler(ctx) {
|
||||||
|
const { config } = ctx.params;
|
||||||
|
const ADCPPSocket = new AirDCPPSocket(config);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ADCPPSocket.connect();
|
||||||
|
console.log("Connected to AirDCPP successfully.");
|
||||||
|
|
||||||
|
ADCPPSocket.addListener(
|
||||||
|
"queue",
|
||||||
|
"queue_bundle_tick",
|
||||||
|
(tickData) => {
|
||||||
|
console.log("Received tick data: ", tickData);
|
||||||
|
this.io.emit("bundleTickUpdate", tickData);
|
||||||
|
},
|
||||||
|
null
|
||||||
|
); // Assuming no specific ID is needed here
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"Error connecting to AirDCPP or setting listener:",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
sleep: (ms: number): Promise<NodeJS.Timeout> => {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
},
|
||||||
|
},
|
||||||
async started() {
|
async started() {
|
||||||
|
this.logger.info("Starting Socket Service...");
|
||||||
|
this.logger.debug("pubClient:", pubClient);
|
||||||
|
this.logger.debug("subClient:", subClient);
|
||||||
|
if (!pubClient || !subClient) {
|
||||||
|
this.logger.error("Redis clients are not initialized!");
|
||||||
|
throw new Error("Redis clients are not initialized!");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Additional checks or logic if necessary
|
||||||
|
if (pubClient.status !== "ready") {
|
||||||
|
await pubClient.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subClient.status !== "ready") {
|
||||||
|
await subClient.connect();
|
||||||
|
}
|
||||||
this.io.on("connection", async (socket) => {
|
this.io.on("connection", async (socket) => {
|
||||||
console.log(
|
console.log(
|
||||||
`socket.io server connected to client with session ID: ${socket.id}`
|
`socket.io server connected to client with session ID: ${socket.id}`
|
||||||
@@ -146,10 +313,7 @@ export default class SocketService extends Service {
|
|||||||
}
|
}
|
||||||
// 2. else, retrieve it from Mongo and "resume" the socket.io connection
|
// 2. else, retrieve it from Mongo and "resume" the socket.io connection
|
||||||
else {
|
else {
|
||||||
console.log(
|
console.log(`Found socketId ${socket.id}, no-op.`);
|
||||||
`Found socketId ${socket.id}, attempting to resume socket.io connection...`
|
|
||||||
);
|
|
||||||
console.log(socket.handshake.query.sessionId);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|||||||
99
services/torrentjobs.service.ts
Normal file
99
services/torrentjobs.service.ts
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
"use strict";
|
||||||
|
import {
|
||||||
|
Context,
|
||||||
|
Service,
|
||||||
|
ServiceBroker,
|
||||||
|
ServiceSchema,
|
||||||
|
Errors,
|
||||||
|
} from "moleculer";
|
||||||
|
import { DbMixin } from "../mixins/db.mixin";
|
||||||
|
import Comic from "../models/comic.model";
|
||||||
|
import BullMqMixin from "moleculer-bullmq";
|
||||||
|
import { pubClient } from "../config/redis.config";
|
||||||
|
const { MoleculerError } = require("moleculer").Errors;
|
||||||
|
|
||||||
|
export default class ImageTransformation extends Service {
|
||||||
|
// @ts-ignore
|
||||||
|
public constructor(
|
||||||
|
public broker: ServiceBroker,
|
||||||
|
schema: ServiceSchema<{}> = { name: "torrentjobs" }
|
||||||
|
) {
|
||||||
|
super(broker);
|
||||||
|
this.parseServiceSchema({
|
||||||
|
name: "torrentjobs",
|
||||||
|
mixins: [DbMixin("comics", Comic), BullMqMixin],
|
||||||
|
settings: {
|
||||||
|
bullmq: {
|
||||||
|
client: pubClient,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
hooks: {},
|
||||||
|
actions: {
|
||||||
|
getTorrentData: {
|
||||||
|
queue: true,
|
||||||
|
rest: "GET /getTorrentData",
|
||||||
|
handler: async (ctx: Context<{ trigger: string }>) => {
|
||||||
|
const { trigger } = ctx.params;
|
||||||
|
console.log(`Recieved ${trigger} as the trigger...`);
|
||||||
|
|
||||||
|
const jobOptions = {
|
||||||
|
jobId: "retrieveTorrentData",
|
||||||
|
name: "bossy",
|
||||||
|
repeat: {
|
||||||
|
every: 10000, // Repeat every 10000 ms
|
||||||
|
limit: 100, // Limit to 100 repeats
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const job = await this.localQueue(
|
||||||
|
ctx,
|
||||||
|
"fetchTorrentData",
|
||||||
|
ctx.params,
|
||||||
|
jobOptions
|
||||||
|
);
|
||||||
|
return job;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fetchTorrentData: {
|
||||||
|
rest: "GET /fetchTorrentData",
|
||||||
|
handler: async (
|
||||||
|
ctx: Context<{
|
||||||
|
birdName: String;
|
||||||
|
}>
|
||||||
|
) => {
|
||||||
|
const repeatableJob = await this.$resolve(
|
||||||
|
"torrentjobs"
|
||||||
|
).getRepeatableJobs();
|
||||||
|
console.info(repeatableJob);
|
||||||
|
console.info(
|
||||||
|
`Scheduled job for fetching torrent data fired.`
|
||||||
|
);
|
||||||
|
// 1. query mongo for infohashes
|
||||||
|
const infoHashes = await this.broker.call(
|
||||||
|
"library.getInfoHashes",
|
||||||
|
{}
|
||||||
|
);
|
||||||
|
// 2. query qbittorrent to see if they exist
|
||||||
|
const torrents: any = await this.broker.call(
|
||||||
|
"qbittorrent.getTorrentRealTimeStats",
|
||||||
|
{ infoHashes }
|
||||||
|
);
|
||||||
|
// 4.
|
||||||
|
await this.broker.call("socket.broadcast", {
|
||||||
|
namespace: "/",
|
||||||
|
event: "AS_TORRENT_DATA",
|
||||||
|
args: [
|
||||||
|
{
|
||||||
|
torrents,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
// 3. If they do, don't do anything
|
||||||
|
// 4. If they don't purge them from mongo
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
methods: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
73
shared/airdcpp.socket.ts
Normal file
73
shared/airdcpp.socket.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
const WebSocket = require("ws");
|
||||||
|
const { Socket } = require("airdcpp-apisocket");
|
||||||
|
|
||||||
|
class AirDCPPSocket {
|
||||||
|
// Explicitly declare properties
|
||||||
|
options; // Holds configuration options
|
||||||
|
socketInstance; // Instance of the AirDCPP Socket
|
||||||
|
|
||||||
|
constructor(configuration: any) {
|
||||||
|
let socketProtocol = configuration.protocol === "https" ? "wss" : "ws";
|
||||||
|
this.options = {
|
||||||
|
url: `${socketProtocol}://${configuration.hostname}/api/v1/`,
|
||||||
|
autoReconnect: true,
|
||||||
|
reconnectInterval: 5000, // milliseconds
|
||||||
|
logLevel: "verbose",
|
||||||
|
ignoredListenerEvents: [
|
||||||
|
"transfer_statistics",
|
||||||
|
"hash_statistics",
|
||||||
|
"hub_counts_updated",
|
||||||
|
],
|
||||||
|
username: configuration.username,
|
||||||
|
password: configuration.password,
|
||||||
|
};
|
||||||
|
// Initialize the socket instance using the configured options and WebSocket
|
||||||
|
this.socketInstance = Socket(this.options, WebSocket);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method to ensure the socket connection is established if required by the library or implementation logic
|
||||||
|
async connect() {
|
||||||
|
// Here we'll check if a connect method exists and call it
|
||||||
|
if (
|
||||||
|
this.socketInstance &&
|
||||||
|
typeof this.socketInstance.connect === "function"
|
||||||
|
) {
|
||||||
|
const sessionInformation = await this.socketInstance.connect();
|
||||||
|
return sessionInformation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method to ensure the socket is disconnected properly if required by the library or implementation logic
|
||||||
|
async disconnect() {
|
||||||
|
// Similarly, check if a disconnect method exists and call it
|
||||||
|
if (
|
||||||
|
this.socketInstance &&
|
||||||
|
typeof this.socketInstance.disconnect === "function"
|
||||||
|
) {
|
||||||
|
await this.socketInstance.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method to post data to an endpoint
|
||||||
|
async post(endpoint: any, data: any = {}) {
|
||||||
|
// Call post on the socket instance, assuming post is a valid method of the socket instance
|
||||||
|
return await this.socketInstance.post(endpoint, data);
|
||||||
|
}
|
||||||
|
async get(endpoint: any, data: any = {}) {
|
||||||
|
// Call post on the socket instance, assuming post is a valid method of the socket instance
|
||||||
|
return await this.socketInstance.get(endpoint, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method to add listeners to the socket instance for handling real-time updates or events
|
||||||
|
async addListener(event: any, handlerName: any, callback: any, id: any) {
|
||||||
|
// Attach a listener to the socket instance
|
||||||
|
return await this.socketInstance.addListener(
|
||||||
|
event,
|
||||||
|
handlerName,
|
||||||
|
callback,
|
||||||
|
id
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AirDCPPSocket;
|
||||||
@@ -74,7 +74,7 @@ const errors = [];
|
|||||||
*/
|
*/
|
||||||
export const extractComicInfoXMLFromRar = async (
|
export const extractComicInfoXMLFromRar = async (
|
||||||
filePath: string,
|
filePath: string,
|
||||||
mimeType: string,
|
mimeType: string
|
||||||
): Promise<any> => {
|
): Promise<any> => {
|
||||||
try {
|
try {
|
||||||
// Create the target directory
|
// Create the target directory
|
||||||
@@ -210,7 +210,7 @@ export const extractComicInfoXMLFromRar = async (
|
|||||||
|
|
||||||
export const extractComicInfoXMLFromZip = async (
|
export const extractComicInfoXMLFromZip = async (
|
||||||
filePath: string,
|
filePath: string,
|
||||||
mimeType: string,
|
mimeType: string
|
||||||
): Promise<any> => {
|
): Promise<any> => {
|
||||||
try {
|
try {
|
||||||
// Create the target directory
|
// Create the target directory
|
||||||
@@ -357,11 +357,17 @@ export const extractFromArchive = async (filePath: string) => {
|
|||||||
switch (mimeType) {
|
switch (mimeType) {
|
||||||
case "application/x-7z-compressed; charset=binary":
|
case "application/x-7z-compressed; charset=binary":
|
||||||
case "application/zip; charset=binary":
|
case "application/zip; charset=binary":
|
||||||
const cbzResult = await extractComicInfoXMLFromZip(filePath, mimeType);
|
const cbzResult = await extractComicInfoXMLFromZip(
|
||||||
|
filePath,
|
||||||
|
mimeType
|
||||||
|
);
|
||||||
return Object.assign({}, ...cbzResult);
|
return Object.assign({}, ...cbzResult);
|
||||||
|
|
||||||
case "application/x-rar; charset=binary":
|
case "application/x-rar; charset=binary":
|
||||||
const cbrResult = await extractComicInfoXMLFromRar(filePath, mimeType);
|
const cbrResult = await extractComicInfoXMLFromRar(
|
||||||
|
filePath,
|
||||||
|
mimeType
|
||||||
|
);
|
||||||
return Object.assign({}, ...cbrResult);
|
return Object.assign({}, ...cbrResult);
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -369,9 +375,8 @@ export const extractFromArchive = async (filePath: string) => {
|
|||||||
"Error inferring filetype for comicinfo.xml extraction."
|
"Error inferring filetype for comicinfo.xml extraction."
|
||||||
);
|
);
|
||||||
throw new MoleculerError({}, 500, "FILETYPE_INFERENCE_ERROR", {
|
throw new MoleculerError({}, 500, "FILETYPE_INFERENCE_ERROR", {
|
||||||
data: { message: "Cannot infer filetype."},
|
data: { message: "Cannot infer filetype." },
|
||||||
});
|
});
|
||||||
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user