File size: 6,848 Bytes
4e83772 03d6d9d 4e83772 03d6d9d 4e83772 03d6d9d 4e83772 03d6d9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | import "dotenv/config";
import { Kafka } from "kafkajs";
import { Deployment } from "./src/models/Deployment";
import { Project } from "./src/models/Projects";
import P_repo from "./src/repositories/project.repository";
import D_repo from "./src/repositories/deployment.repository";
import AnalyticsRepo from "./src/repositories/analytics.repository";
import mongoose, { Types } from "mongoose";
import connectDb from "./src/config/mongo.config";
import { User } from "./src/models/User";
import { client } from "./src/config/clickhouse.config";
import { generateSlug } from "random-word-slugs";
import { nanoid } from "./src/utils/generateNanoid";
import crypto from "crypto";
import { OtpModel } from "./src/models/Otp";
import { v4 as uuidV4 } from "uuid";
function formatTimeWithSeconds(input: Date | string | number): string {
const date = input instanceof Date ? input : new Date(input);
if (isNaN(date.getTime())) {
throw new Error("Invalid date input");
}
let hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const ampm = hours >= 12 ? "PM" : "AM";
hours = hours % 12 || 12; // Convert 0–23 → 1–12 range
// Pad with leading zeros
const hh = String(hours).padStart(2, "0");
const mm = String(minutes).padStart(2, "0");
const ss = String(seconds).padStart(2, "0");
return `${hh}:${mm}:${ss} ${ampm}`;
}
console.log("--------------------------------------------------------------------------------------------------------------");
async function mongodbData() {
try {
await connectDb();
const p = new P_repo();
const de = new D_repo();
// const obj = new OtpModel({ userId: "68c8d40ce28583b09f575555", otpHash: "heysuuu", expiresAt: new Date(Date.now() + 60 * 1000) })
// const saved = await OtpModel.find()
// console.log(saved)
// await Promise.all(dpls.map(async (d) => {
await Deployment.updateMany({ _id: "697dc843d79bd147c535419a" }, { status: "QUEUED" });
// }))
console.log(
await Project.updateMany(
{ _id: "69246647869c614a349015fc" },
{
status: "QUEUED",
lastDeployment: null,
tempDeployment: "697dc843d79bd147c535419a",
currentDeployment: null,
},
),
);
} catch (error) {
console.log(error);
} finally {
process.exit(0);
}
}
// mongodbData().then(async () => await mongoose.disconnect());
async function commitAllMessages() {
const kafka = new Kafka({
clientId: `api-server`,
brokers: ["kafka-lynfera-renderstest446446-7987.f.aivencloud.com:11100"],
ssl: {
ca: process.env.KAFKA_CA?.replace(/\\n/g, "\n")
},
sasl: {
mechanism: "plain",
username: process.env.KAFKA_USERNAME as string,
password: process.env.KAFKA_PASSWORD as string,
},
});
const topic = "deployment.logs";
const groupId = "lynfera-logs-group";
const admin = kafka.admin();
await admin.connect();
try {
const topicMetadata = await admin.fetchTopicMetadata({ topics: [topic] });
const partitions = topicMetadata.topics[0].partitions.map((p) => p.partitionId);
const endOffsets = await admin.fetchTopicOffsets(topic);
const offsetsToCommit = endOffsets.map(({ partition, offset }) => ({
topic,
partition,
offset,
}));
await admin.setOffsets({ groupId, topic, partitions: offsetsToCommit });
console.log("configs====>>>>>>>", { partitions });
console.log(`✅ All uncommitted messages marked as consumed for group "${groupId}" on topic "${topic}".`);
} catch (err) {
console.error("❌ Error committing offsets:", err);
} finally {
await admin.disconnect();
}
}
// commitAllMessages();
// --------------------------------
async function getClickhouseData() {
// await client.insert({
// table: "log_events_v2",
// values: [
// {
// event_id: uuidV4(),
// info: "WARN",
// deployment_id: "--------------------------------",
// project_id: "69246647869c614a349015fc",
// log: "Hi Mom",
// report_time: new Date().getTime(),
// sequence: 69,
// },
// ],
// format: "JSONEachRow",
// });
// return
const data = await client.query({
query: `SELECT ip, toTimeZone(timestamp, 'Asia/Kolkata') from analytics where project_id='6934502adfa2d8c1c254aabc'`,
// format: "JSON",
});
const datas = await data.json();
console.log(datas.data.length);
console.log(datas.data);
// await client.query({
// query: "TRUNCATE analytics"
// })
}
// getClickhouseData().then(() => process.exit(0));
async function idChecker() {
const obj = new Set();
const id = "";
return;
for (let i = 0; i < 50; i++) {
if (obj.has(id)) {
console.log(" found at ", i, id);
}
try {
obj.add(id);
} catch (error) {
console.log(i, " _ _ __ _ _");
throw error;
}
}
console.log(obj);
}
// idChecker()
async function gitPushStatusChanger() {
console.log("Starting ...");
const repoUser = "AmalJose664/Three-d-Projects"
const res = await fetch(`https://api.github.com/repos/${repoUser}/check-runs/${71949271798}`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${"token here"}`,
Accept: "application/vnd.github+json",
"Content-Type": "application/json",
},
body: JSON.stringify({
status: "completed",
conclusion: "cancelled", // or "failure"
}),
});
// const res = await fetch(`https://api.github.com/repos//${repoUser}/check-runs`, {
// method: "POST",
// headers: {
// Authorization: `Bearer ${installationToken}`,
// Accept: "application/vnd.github+json",
// "Content-Type": "application/json",
// },
// body: JSON.stringify({
// name: "Lynfera Deploy",
// head_sha: "5ea33e0389101cbc2a6122f48397c07761692a28",
// status: "in_progress",
// }),
// });
const check = await res.json();
console.log({ check });
}
//gitPushStatusChanger();
function generateOTP(length = 6) {
return Math.floor(10 ** (length - 1) + Math.random() * 9 * 10 ** (length - 1));
}
async function sendEmailOTP(email) {
const otp = generateOTP();
try {
const response = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": ""
},
body: JSON.stringify({
sender: {
name: "Your App",
email: "callbackff200002@gmail.com"
},
to: [
{ email: email }
],
subject: "Your OTP Code",
htmlContent: `
<div style="font-family: Arial; padding: 10px;">
<h2>Your OTP Code</h2>
<p>Your OTP is:</p>
<h1 style="letter-spacing: 5px;">${otp}</h1>
<p>This code is valid for 5 minutes.</p>
</div>
`
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(JSON.stringify(data));
}
console.log("OTP email sent:", data);
return otp; // store in DB/cache for verification
} catch (error) {
console.error("Error sending OTP:", error.message);
}
}
// sendEmailOTP("renderstest446446@gmail.com") |