Compare commits

...

57 commits

Author SHA1 Message Date
3d8306b225 changing source of games 2024-09-21 13:25:42 +03:00
d3460f8871 logs added 2024-07-31 21:53:04 +03:00
15932a0c9d changing the cron to every min 2024-02-04 15:31:58 +02:00
3fef736821 changing the cron to be every day at 10 am 2024-02-04 13:40:17 +02:00
486f334b4a changing the logs 2024-02-04 13:38:35 +02:00
e133b49ee9 adding more headers 2024-02-04 13:10:12 +02:00
59552698e9 adding headers to each request to haifa 2024-02-04 13:05:18 +02:00
3ad063cbc2 remove log file from git 2024-02-04 13:01:06 +02:00
55b7b99e48 ran tsc locally 2024-02-04 13:00:14 +02:00
ea7e224c9e ran tsc locally 2024-02-04 12:56:26 +02:00
d5408c359b added try catch to haifa 2024-02-04 12:55:47 +02:00
265a182d8f added try catch to haifa 2024-02-04 12:54:32 +02:00
dbdf76554b remove https 2024-02-04 12:52:15 +02:00
daea0c9cfb invoke cron every min 2024-02-04 11:45:59 +02:00
54483b96b6 adding logs outputs of handeling events 2024-01-23 11:53:52 +02:00
522d30d7dd remove unused code 2023-09-10 13:02:43 +03:00
dc57073067 dockerfile - add TZ env var + title has changed to 2 teams playing 2023-09-10 09:51:08 +03:00
0362566c2a remove dist from repo 2023-09-10 09:50:05 +03:00
b07d434bf3 fixing posponded games 2023-08-21 09:35:44 +03:00
5588c999a7 finding dynamiclly the date and time from the headers 2023-08-15 15:01:11 +03:00
fd7e2377e1 testing 2023-08-13 11:44:41 +03:00
427423d3e8 remove the Value from the comment 2023-08-06 15:17:41 +03:00
87582b72ee build inside repo the dist 2023-08-06 11:25:52 +03:00
1f59ccfb2c cleaning 2023-08-06 10:48:24 +03:00
3aeb79f054 clean up 2023-08-06 00:35:07 +03:00
92a256c784 remove node_modules 2023-07-26 15:16:04 +03:00
fd4b483a6c remove node_modules 2023-07-26 15:15:51 +03:00
f95ed86012 remove node_modules 2023-07-26 15:15:38 +03:00
95b2f4283b done manually 2023-07-26 15:14:58 +03:00
43bb990df5 adding catch 2023-07-26 14:31:24 +03:00
a1ae8c98d1 testing 2023-07-26 14:14:10 +03:00
bbf1865f1a adding node_modules + dist 2023-07-26 14:02:08 +03:00
7675d627d8 adding node_modules + dist 2023-07-26 14:01:58 +03:00
18c3fcb06a start modify 2023-07-26 13:31:35 +03:00
a022002c36 start modify 2023-07-26 13:31:16 +03:00
d408a385bb google calendar enabled 2023-07-26 13:17:32 +03:00
Kfir Dayan
90bb926341 removed google api + changing game info 2023-04-16 14:53:59 +03:00
Kfir Dayan
0fea123354 removed google api + changing game info 2023-04-16 14:53:39 +03:00
Kfir Dayan
d512ca8197 fixing uuid module not found error 2023-04-04 13:44:58 +03:00
Kfir Dayan
9547cedf4b remove_google_api_temporary 2023-04-04 13:03:10 +03:00
Kfir Dayan
b6455824e6 small change in .gitignore & mv the ec2 key into the project 2023-04-04 12:52:18 +03:00
Kfir Dayan
b90d9524ff creating ical file as well 2023-04-04 12:31:20 +03:00
Kfir Dayan
54aec5450f install ical 2023-04-04 11:41:17 +03:00
Kfir Dayan
332f363efc added bash script for build and push 2023-04-03 20:09:44 +03:00
Kfir Dayan
52c8516a1e changed the 404 msg 2023-04-03 20:06:02 +03:00
Kfir Dayan
3a7803ef2b add bash script 2023-04-03 20:05:25 +03:00
Kfir Dayan
7859110d97 dockerfile add tsc command 2023-04-03 19:52:41 +03:00
Kfir Dayan
cfc2d3bc9a 404 2023-04-02 17:03:31 +03:00
8b04c510a7 dockerizing_project (#3)
Co-authored-by: Kfir Dayan <kfirdayan@Kfirs-MacBook-Pro.local>
Reviewed-on: #3

added docker files
2023-04-02 13:43:22 +00:00
Kfir Dayan
09f43fefe6 re-unite the scripts 2023-04-02 15:36:11 +03:00
Kfir Dayan
377f641d49 cron for every min 2023-04-02 11:18:17 +03:00
Kfir Dayan
5e0e203fa3 adding cron 2023-04-02 11:13:43 +03:00
Kfir Dayan
831dfaaea0 every day at 10am the script runs 2023-04-02 11:10:44 +03:00
Kfir Dayan
4360499dd0 git ignoring dist 2023-04-02 10:15:25 +03:00
Kfir Dayan
d6d682a4b0 the web server returns a static files 2023-03-30 13:22:24 +03:00
Kfir Dayan
75c43c3443 install express + created a simple web-server 2023-03-30 09:41:14 +03:00
Kfir Dayan
a1b1c326f8 fix bug - same uuid for each event is a bug 2023-03-30 09:05:25 +03:00
19 changed files with 665 additions and 358 deletions

3
.dockerignore Normal file
View file

@ -0,0 +1,3 @@
node_modules
npm-debug.log
tmp

View file

@ -1,9 +1,11 @@
# Google
SERPAPI_KEY
# Google # Google
GOOGLE_CALENDAR_ID GOOGLE_CALENDAR_ID
GOOGLE_PROJECT_NUMBER GOOGLE_PROJECT_NUMBER
GOOGLE_CLIENT_EMAIL GOOGLE_CLIENT_EMAIL
GOOGLE_PRIVATE_KEY GOOGLE_PRIVATE_KEY
GOOGLE_KEY_ID
GOOGLE_CLIENT_ID GOOGLE_CLIENT_ID
GOOGLE_CLIENT_SECRET GOOGLE_CLIENT_SECRET

12
.gitignore vendored
View file

@ -2,7 +2,8 @@
node_modules node_modules
#javascript build files # #javascript build files #
public # public/**/*
dist/**/*
# Tmp files # # Tmp files #
tmp tmp
@ -12,4 +13,11 @@ tmp
.env .env
config/client_google_auth.json config/client_google_auth.json
## output ## ## Docker ##
build_image.sh
push_dockerhub.sh
# keys #
keys/**/*
cron.log

16
Dockerfile Normal file
View file

@ -0,0 +1,16 @@
FROM node:16
ENV TZ=Asia/Jerusalem
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm install -g typescript
COPY . .
EXPOSE ${PORT}
RUN tsc
CMD [ "npm", "start" ]

95
dist/GameSource.js vendored Normal file
View file

@ -0,0 +1,95 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("dotenv").config();
const axios_1 = __importDefault(require("axios"));
const moment_1 = __importDefault(require("moment"));
class GameSource {
async getGamesFromHaifa(logger) {
console.log("Trying to get games from Haifa...");
try {
// Get the current date and time in the required format
const currentDate = (0, moment_1.default)().format("DD/MM/YYYY HH:mm");
// Construct the filters object with the current date
const filters = {
date: {
startDate: currentDate,
endDate: "",
},
league: "",
session: "",
gamesDirection: "1",
};
// Encode the filters for the URL
const filtersParam = encodeURIComponent(JSON.stringify(filters));
// Construct the API URL with the encoded filters
const sourceUrl = `https://api.mhaifafc.com/api/content/games-lobby?filters=${filtersParam}&start=0&limit=20&sortDirection=ASC&app=web&lang=he`;
// Get the authorization token from environment variables
const authorizationToken = process.env.HAIFA_API_AUTH_TOKEN;
// Set up the request headers
const headers = {
Accept: "*/*",
"Accept-Language": "en-US,en;q=0.7",
Authorization: `Bearer ${authorizationToken}`,
"User-Agent": "Mozilla/5.0",
Origin: "https://www.mhaifafc.com",
Referer: "https://www.mhaifafc.com/",
};
// Make the API request
const response = await axios_1.default.get(sourceUrl, {
headers,
responseType: "json",
responseEncoding: "utf8", // Ensure UTF-8 encoding
});
// Extract the games data from the response
const gamesData = response.data.games.items;
const games = [];
// Loop through each game and construct the GoogleCalendarEvent objects
for (const game of gamesData) {
const gameDetails = game.gameDetails;
const gameTime = gameDetails.gameTime; // ISO string
const isFinalGameDate = gameDetails.isFinalGameDate;
const gameLocation = gameDetails.gameLocation;
// Skip games without a game time
if (!gameTime)
continue;
const hostTeam = game.hostTeam;
const guestTeam = game.guestTeam;
// Get team names
const hostTeamName = hostTeam.teamName;
const guestTeamName = guestTeam.teamName;
const summary = `${hostTeamName} vs. ${guestTeamName}`;
// Include a note if the game date is not final
let description = `${hostTeamName} vs. ${guestTeamName}`;
if (!isFinalGameDate) {
description += " (Date and time are subject to change)";
}
// Calculate start and end times
const startDateTime = (0, moment_1.default)(gameTime).toISOString();
const endDateTime = (0, moment_1.default)(gameTime).add(2, "hours").toISOString();
// Add the event to the games array
games.push({
summary: summary,
location: gameLocation,
description: description,
start: {
dateTime: startDateTime,
timeZone: "Asia/Jerusalem",
},
end: {
dateTime: endDateTime,
timeZone: "Asia/Jerusalem",
},
});
}
return games;
}
catch (error) {
console.error(error);
return [];
}
}
}
exports.default = GameSource;

88
dist/GoogleCalendar.js vendored Normal file
View file

@ -0,0 +1,88 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const google_auth_library_1 = require("google-auth-library");
const googleapis_1 = require("googleapis");
require("dotenv").config();
const env = process.env;
class GoogleCalendar {
constructor() {
this.gamesMap = {};
this.clientSecret = env.GOOGLE_CLIENT_SECRET;
this.clientId = env.GOOGLE_CLIENT_ID;
this.calenderId = env.GOOGLE_CALENDAR_ID;
this.clientEmail = env.GOOGLE_CLIENT_EMAIL;
this.googlePrivateKey = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n");
}
async init() {
console.log("INIT GOOGLE CALENDAR");
const jwtClient = await this.authorize();
this.calendar = googleapis_1.google.calendar({ version: "v3", auth: jwtClient });
}
async authorize() {
console.log("AUTHORIZE GOOGLE CALENDAR");
this.JWT_client = new google_auth_library_1.JWT({
email: this.clientEmail,
key: this.googlePrivateKey,
scopes: ["https://www.googleapis.com/auth/calendar"],
});
const { access_token } = await this.JWT_client.authorize();
this.token = access_token;
if (!this.token) {
throw new Error("Failed to connect to google calendar");
}
console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY");
return this.JWT_client;
}
async updateNewEvent(upcomingEvents) {
// console.log(upcomingEvents)
setTimeout(async () => {
upcomingEvents.forEach(async (event) => {
console.log("UPDATE NEW EVENT", upcomingEvents);
const options = {
auth: this.JWT_client,
calendarId: this.calenderId,
resource: {
summary: event.summary,
location: event.location,
description: event.description,
start: {
dateTime: event.start.dateTime,
timeZone: "Asia/Jerusalem",
},
end: { dateTime: event.end.dateTime, timeZone: "Asia/Jerusalem" },
sendNotifications: true,
},
};
await this.calendar.events.insert(options, function (err, event) {
if (err) {
console.log("There was an error contacting the Calendar service: " + err);
return;
}
console.log(event.description + " created");
});
});
}, 3000);
}
async isDuplicateEvent(startTime, endTime, title) {
if (this.gamesMap[startTime]) {
console.log("duplicate event");
return true;
}
this.gamesMap[startTime] = true;
console.log("checking for duplicate event");
try {
const response = await this.calendar.events.list({
calendarId: this.calenderId,
timeMin: startTime,
timeMax: endTime,
q: title, // Search for events with the same title
});
return response.data.items.length > 0;
}
catch (error) {
console.error(error.message);
return false;
}
}
}
exports.default = GoogleCalendar;

68
dist/index.js vendored Normal file
View file

@ -0,0 +1,68 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const GameSource_1 = __importDefault(require("./GameSource"));
const GoogleCalendar_1 = __importDefault(require("./GoogleCalendar"));
const dotenv_1 = __importDefault(require("dotenv"));
const node_cron_1 = __importDefault(require("node-cron"));
const fs_1 = __importDefault(require("fs")); // Importing fs for logging
dotenv_1.default.config();
class App {
constructor() {
this.gameSource = new GameSource_1.default();
this.googleCalendar = new GoogleCalendar_1.default();
}
async startCronJob() {
this.writeLog('START Haifa Reminder'); // Log when the cron job starts
const newGamesAdded = [];
await this.googleCalendar.init();
try {
const games = await this.gameSource.getGamesFromHaifa(this.writeLog);
for (const game of games) {
const isDuplicateEvent = await this.googleCalendar.isDuplicateEvent(game.start.dateTime, game.end.dateTime, game.summary);
console.log(game);
if (!isDuplicateEvent) {
newGamesAdded.push(game);
console.log("Event does not exist");
await this.googleCalendar.updateNewEvent([game]);
}
else {
console.log("Event already exists");
}
}
if (newGamesAdded.length > 0) {
console.log("New games added:", newGamesAdded);
}
else {
console.log("No new games were Added!");
}
this.writeLog('Successfully ran project');
}
catch (error) {
this.writeLog("Error in cron job:" + error.message);
}
finally {
this.writeLog('END CRON JOB'); // Log when the cron job ends
}
}
writeLog(message) {
const timestamp = new Date().toISOString();
const logMessage = `${timestamp} - ${message}\n`;
// Write to log file synchronously
fs_1.default.appendFileSync('cron.log', logMessage);
console.log(logMessage); // Optional: also log to console
}
}
const app = new App();
node_cron_1.default.schedule('* * * * *', () => {
console.log('Running startCronJob at 10:00 AM Jerusalem time');
app.startCronJob().catch((error) => {
console.error("Error in scheduled cron job:", error.message);
app.writeLog(`ERROR: ${error.message}`); // Log any errors
});
}, {
scheduled: true,
timezone: "Asia/Jerusalem"
});

2
dist/types/index.js vendored Normal file
View file

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View file

@ -1,91 +0,0 @@
BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:https://mhaifafc.com/
METHOD:PUBLISH
X-PUBLISHED-TTL:PT1H
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230401T170000Z
DTEND:20230401T190000Z
DESCRIPTION:Maccabi Haifa vs. H Be'er Sheva
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230404T173000Z
DTEND:20230404T193000Z
DESCRIPTION:Maccabi Tel aviv vs. Maccabi Haifa
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230408T170000Z
DTEND:20230408T190000Z
DESCRIPTION:Maccabi Haifa vs. Maccabi Netanya
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230415T153000Z
DTEND:20230415T173000Z
DESCRIPTION:Hapoel Jerusalem vs. Maccabi Haifa
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230423T173000Z
DTEND:20230423T193000Z
DESCRIPTION:F.C Ashdod vs. Maccabi Haifa
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
BEGIN:VEVENT
UID:cba9cb6a-56ae-4730-ba62-b98032e7767a
SUMMARY:Maccabi Haifa F.C.
DTSTAMP:20230329T074644Z
DTSTART:20230501T173000Z
DTEND:20230501T193000Z
DESCRIPTION:H Be'er Sheva vs. Maccabi Haifa
URL:https://mhaifafc.com/
LOCATION:Sammy Ofer Stadium
STATUS:CONFIRMED
CATEGORIES:
ORGANIZER;CN=Maccabi Haifa F.C.
X-MICROSOFT-CDO-BUSYSTATUS:BUSY
END:VEVENT
END:VCALENDAR

245
package-lock.json generated
View file

@ -7,30 +7,67 @@
"dependencies": { "dependencies": {
"axios": "^1.3.4", "axios": "^1.3.4",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"googleapis": "^113.0.0", "googleapis": "^122.0.0",
"ics": "^3.1.0",
"moment": "^2.29.4", "moment": "^2.29.4",
"node-html-parser": "^6.1.5" "moment-timezone": "^0.5.43",
"node-cron": "^3.0.3",
"node-html-parser": "^6.1.5",
"uuid": "^9.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^18.15.5" "@types/express": "^4.17.17",
"@types/node": "^18.15.5",
"@types/node-cron": "^3.0.11",
"typescript": "^5.0.3"
} }
}, },
"node_modules/@babel/runtime": { "node_modules/@types/body-parser": {
"version": "7.21.0", "version": "1.19.2",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.21.0.tgz", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.2.tgz",
"integrity": "sha512-xwII0//EObnq89Ji5AKYQaRYiW/nZ3llSv29d49IuxPhKbtJoLP+9QUUZ4nVragQVtaVGeZrpB+ZtG/Pdy/POw==", "integrity": "sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==",
"dev": true,
"dependencies": { "dependencies": {
"regenerator-runtime": "^0.13.11" "@types/connect": "*",
}, "@types/node": "*"
"engines": {
"node": ">=6.9.0"
} }
}, },
"node_modules/@types/lodash": { "node_modules/@types/connect": {
"version": "4.14.192", "version": "3.4.35",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.192.tgz", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.35.tgz",
"integrity": "sha512-km+Vyn3BYm5ytMO13k9KTp27O75rbQ0NFw+U//g+PX7VZyjCioXaRFisqSIJRECljcTv73G3i6BpglNGHgUQ5A==" "integrity": "sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/express": {
"version": "4.17.17",
"resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.17.tgz",
"integrity": "sha512-Q4FmmuLGBG58btUnfS1c1r/NQdlp3DMfGDGig8WhfpA2YRUtEkxAjkZb0yvplJGYdF1fsQ81iMDcH24sSCNC/Q==",
"dev": true,
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^4.17.33",
"@types/qs": "*",
"@types/serve-static": "*"
}
},
"node_modules/@types/express-serve-static-core": {
"version": "4.17.33",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.33.tgz",
"integrity": "sha512-TPBqmR/HRYI3eC2E5hmiivIzv+bidAfXofM+sbonAGvyDhySGw9/PQZFt2BLOrjUUR++4eJVpx6KnLQK1Fk9tA==",
"dev": true,
"dependencies": {
"@types/node": "*",
"@types/qs": "*",
"@types/range-parser": "*"
}
},
"node_modules/@types/mime": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/mime/-/mime-3.0.1.tgz",
"integrity": "sha512-Y4XFY5VJAuw0FgAqPNd6NNoV44jbq9Bz2L7Rh/J6jLTiHBSBJa9fxqQIvkIld4GsoDOcCbvzOUAbLPsSKKg+uA==",
"dev": true
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "18.15.5", "version": "18.15.5",
@ -38,6 +75,34 @@
"integrity": "sha512-Ark2WDjjZO7GmvsyFFf81MXuGTA/d6oP38anyxWOL6EREyBKAxKoFHwBhaZxCfLRLpO8JgVXwqOwSwa7jRcjew==", "integrity": "sha512-Ark2WDjjZO7GmvsyFFf81MXuGTA/d6oP38anyxWOL6EREyBKAxKoFHwBhaZxCfLRLpO8JgVXwqOwSwa7jRcjew==",
"dev": true "dev": true
}, },
"node_modules/@types/node-cron": {
"version": "3.0.11",
"resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz",
"integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==",
"dev": true
},
"node_modules/@types/qs": {
"version": "6.9.7",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.7.tgz",
"integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==",
"dev": true
},
"node_modules/@types/range-parser": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.4.tgz",
"integrity": "sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==",
"dev": true
},
"node_modules/@types/serve-static": {
"version": "1.15.1",
"resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.1.tgz",
"integrity": "sha512-NUo5XNiAdULrJENtJXZZ3fHtfMolzZwczzBbnAeBbqBwG+LaG6YaJtuwzwGSQZ2wsCrxjEhNNjAkKigy3n8teQ==",
"dev": true,
"dependencies": {
"@types/mime": "*",
"@types/node": "*"
}
},
"node_modules/agent-base": { "node_modules/agent-base": {
"version": "6.0.2", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@ -308,23 +373,23 @@
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A=="
}, },
"node_modules/gaxios": { "node_modules/gaxios": {
"version": "5.1.0", "version": "5.1.3",
"resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.0.tgz", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.3.tgz",
"integrity": "sha512-aezGIjb+/VfsJtIcHGcBSerNEDdfdHeMros+RbYbGpmonKWQCOVOes0LVZhn1lDtIgq55qq0HaxymIoae3Fl/A==", "integrity": "sha512-95hVgBRgEIRQQQHIbnxBXeHbW4TqFk4ZDJW7wmVtvYar72FdhRIo1UGOLS2eRAKCPEdPBWu+M7+A33D9CdX9rA==",
"dependencies": { "dependencies": {
"extend": "^3.0.2", "extend": "^3.0.2",
"https-proxy-agent": "^5.0.0", "https-proxy-agent": "^5.0.0",
"is-stream": "^2.0.0", "is-stream": "^2.0.0",
"node-fetch": "^2.6.7" "node-fetch": "^2.6.9"
}, },
"engines": { "engines": {
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/gcp-metadata": { "node_modules/gcp-metadata": {
"version": "5.2.0", "version": "5.3.0",
"resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-5.2.0.tgz", "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-5.3.0.tgz",
"integrity": "sha512-aFhhvvNycky2QyhG+dcfEdHBF0FRbYcf39s6WNHUDysKSrbJ5vuFbjydxBcmewtXeV248GP8dWT3ByPNxsyHCw==", "integrity": "sha512-FNTkdNEnBdlqF2oatizolQqNANMrcqJt6AAYt99B3y1aLLC8Hc5IOBb+ZnnzllodEEf6xMBp6wRcBbc16fa65w==",
"dependencies": { "dependencies": {
"gaxios": "^5.0.0", "gaxios": "^5.0.0",
"json-bigint": "^1.0.0" "json-bigint": "^1.0.0"
@ -347,16 +412,16 @@
} }
}, },
"node_modules/google-auth-library": { "node_modules/google-auth-library": {
"version": "8.7.0", "version": "8.9.0",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-8.7.0.tgz", "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-8.9.0.tgz",
"integrity": "sha512-1M0NG5VDIvJZEnstHbRdckLZESoJwguinwN8Dhae0j2ZKIQFIV63zxm6Fo6nM4xkgqUr2bbMtV5Dgo+Hy6oo0Q==", "integrity": "sha512-f7aQCJODJFmYWN6PeNKzgvy9LI2tYmXnzpNDHEjG5sDNPgGb2FXQyTBnXeSH+PAtpKESFD+LmHw3Ox3mN7e1Fg==",
"dependencies": { "dependencies": {
"arrify": "^2.0.0", "arrify": "^2.0.0",
"base64-js": "^1.3.0", "base64-js": "^1.3.0",
"ecdsa-sig-formatter": "^1.0.11", "ecdsa-sig-formatter": "^1.0.11",
"fast-text-encoding": "^1.0.0", "fast-text-encoding": "^1.0.0",
"gaxios": "^5.0.0", "gaxios": "^5.0.0",
"gcp-metadata": "^5.0.0", "gcp-metadata": "^5.3.0",
"gtoken": "^6.1.0", "gtoken": "^6.1.0",
"jws": "^4.0.0", "jws": "^4.0.0",
"lru-cache": "^6.0.0" "lru-cache": "^6.0.0"
@ -380,9 +445,9 @@
} }
}, },
"node_modules/googleapis": { "node_modules/googleapis": {
"version": "113.0.0", "version": "122.0.0",
"resolved": "https://registry.npmjs.org/googleapis/-/googleapis-113.0.0.tgz", "resolved": "https://registry.npmjs.org/googleapis/-/googleapis-122.0.0.tgz",
"integrity": "sha512-gsknEobaFuS+ACraCL3w22pAqeg1HselNhiSjcF5p2d2t2HB3QchbRDrFCfZ0wc4gKLYUBdmGzulCmRRL5qNXw==", "integrity": "sha512-n8Gt7j9LzSkhQEGPOrcLBKxllTvW/0v6oILuwszL/zqgelNsGJYXVqPJllgJJ6RM7maJ6T35UBeYqI6GQ/IlJg==",
"dependencies": { "dependencies": {
"google-auth-library": "^8.0.2", "google-auth-library": "^8.0.2",
"googleapis-common": "^6.0.0" "googleapis-common": "^6.0.0"
@ -462,15 +527,6 @@
"node": ">= 6" "node": ">= 6"
} }
}, },
"node_modules/ics": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/ics/-/ics-3.1.0.tgz",
"integrity": "sha512-O48TZKyLYagLlXoZwDmjetXc6SoT54wFkTu2MEYe7zse8kL+C/dgSynYCjRG1OTAv3iHtGtG0PWKG81LbcrKFA==",
"dependencies": {
"nanoid": "^3.1.23",
"yup": "^0.32.9"
}
},
"node_modules/is-stream": { "node_modules/is-stream": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
@ -509,16 +565,6 @@
"safe-buffer": "^5.0.1" "safe-buffer": "^5.0.1"
} }
}, },
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
},
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw=="
},
"node_modules/lru-cache": { "node_modules/lru-cache": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@ -557,37 +603,45 @@
"node": "*" "node": "*"
} }
}, },
"node_modules/moment-timezone": {
"version": "0.5.43",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.43.tgz",
"integrity": "sha512-72j3aNyuIsDxdF1i7CEgV2FfxM1r6aaqJyLB2vwb33mXYyoyLly+F1zbWqhA3/bVIoJ4szlUoMbUnVdid32NUQ==",
"dependencies": {
"moment": "^2.29.4"
},
"engines": {
"node": "*"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"node_modules/nanoclone": { "node_modules/node-cron": {
"version": "0.2.1", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/nanoclone/-/nanoclone-0.2.1.tgz", "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
"integrity": "sha512-wynEP02LmIbLpcYw8uBKpcfF6dmg2vcpKqxeH5UcoKEYdExslsdUA4ugFauuaeYdTB76ez6gJW8XAZ6CgkXYxA==" "integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
}, "dependencies": {
"node_modules/nanoid": { "uuid": "8.3.2"
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.6.tgz",
"integrity": "sha512-BGcqMMJuToF7i1rt+2PWSNVnWIkGCU78jBG3RxO/bZlnZPK2Cmi2QaffxGO/2RvWi9sL+FAiRiXMgsyxQ1DIDA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"bin": {
"nanoid": "bin/nanoid.cjs"
}, },
"engines": { "engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" "node": ">=6.0.0"
}
},
"node_modules/node-cron/node_modules/uuid": {
"version": "8.3.2",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
"bin": {
"uuid": "dist/bin/uuid"
} }
}, },
"node_modules/node-fetch": { "node_modules/node-fetch": {
"version": "2.6.9", "version": "2.6.12",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.9.tgz", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==", "integrity": "sha512-C/fGU2E8ToujUivIO0H+tpQ6HWo4eEmchoPIoXtxCrVghxdKq+QOHqEZW7tuP3KlV3bC8FRMO5nMCC7Zm1VP6g==",
"dependencies": { "dependencies": {
"whatwg-url": "^5.0.0" "whatwg-url": "^5.0.0"
}, },
@ -639,20 +693,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/property-expr": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/property-expr/-/property-expr-2.0.5.tgz",
"integrity": "sha512-IJUkICM5dP5znhCckHSv30Q4b5/JA5enCtkRHYaOVOAocnH/1BQEYTC5NMfT3AVl/iXKdr3aqQbQn9DxyWknwA=="
},
"node_modules/proxy-from-env": { "node_modules/proxy-from-env": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
}, },
"node_modules/qs": { "node_modules/qs": {
"version": "6.11.1", "version": "6.11.2",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.11.1.tgz", "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz",
"integrity": "sha512-0wsrzgTz/kAVIeuxSjnpGC56rzYtr6JT/2BwEvMaPhFIoYa1aGO8LbzuU1R0uUYQkLpWBTOj0l/CLAJB64J6nQ==", "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==",
"dependencies": { "dependencies": {
"side-channel": "^1.0.4" "side-channel": "^1.0.4"
}, },
@ -663,11 +712,6 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/regenerator-runtime": {
"version": "0.13.11",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
"integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg=="
},
"node_modules/safe-buffer": { "node_modules/safe-buffer": {
"version": "5.2.1", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@ -700,16 +744,24 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/toposort": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/toposort/-/toposort-2.0.2.tgz",
"integrity": "sha512-0a5EOkAUp8D4moMi2W8ZF8jcga7BgZd91O/yabJCFY8az+XSzeGyTKs0Aoo897iV1Nj6guFq8orWDS96z91oGg=="
},
"node_modules/tr46": { "node_modules/tr46": {
"version": "0.0.3", "version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
}, },
"node_modules/typescript": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.3.tgz",
"integrity": "sha512-xv8mOEDnigb/tN9PSMTwSEqAnUvkoXMQlicOb0IUVDBSQCgBSaAAROUZYy2IcUy5qU6XajK5jjjO7TMWqBTKZA==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=12.20"
}
},
"node_modules/url-template": { "node_modules/url-template": {
"version": "2.0.8", "version": "2.0.8",
"resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz", "resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz",
@ -741,23 +793,6 @@
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"node_modules/yup": {
"version": "0.32.11",
"resolved": "https://registry.npmjs.org/yup/-/yup-0.32.11.tgz",
"integrity": "sha512-Z2Fe1bn+eLstG8DRR6FTavGD+MeAwyfmouhHsIUgaADz8jvFKbO/fXc2trJKZg+5EBjh4gGm3iU/t3onKlXHIg==",
"dependencies": {
"@babel/runtime": "^7.15.4",
"@types/lodash": "^4.14.175",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"nanoclone": "^0.2.1",
"property-expr": "^2.0.4",
"toposort": "^2.0.2"
},
"engines": {
"node": ">=10"
}
} }
} }
} }

View file

@ -2,15 +2,22 @@
"dependencies": { "dependencies": {
"axios": "^1.3.4", "axios": "^1.3.4",
"dotenv": "^16.0.3", "dotenv": "^16.0.3",
"googleapis": "^113.0.0", "googleapis": "^122.0.0",
"ics": "^3.1.0",
"moment": "^2.29.4", "moment": "^2.29.4",
"node-html-parser": "^6.1.5" "moment-timezone": "^0.5.43",
"node-cron": "^3.0.3",
"node-html-parser": "^6.1.5",
"uuid": "^9.0.0"
}, },
"scripts": { "scripts": {
"dev": "nodemon public/index.js" "dev": "nodemon dist/index.js",
"build": "npx tsc",
"start": "node dist/index.js"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^18.15.5" "@types/express": "^4.17.17",
"@types/node": "^18.15.5",
"@types/node-cron": "^3.0.11",
"typescript": "^5.0.3"
} }
} }

4
restart.sh Normal file
View file

@ -0,0 +1,4 @@
#!/bin/bash
docker stop haifareminder
docker rm haifareminder
docker run -p 3000:3000 -d --restart=unless-stopped --name haifareminder docker.io/kfda89/haifareminder

View file

@ -1,63 +1,106 @@
require('dotenv').config(); require("dotenv").config();
import axios from "axios"; import axios from "axios";
import { GoogleCalendarEvent } from "./types"; import { GoogleCalendarEvent } from "./types";
import { parse } from 'node-html-parser'; import moment from "moment";
import moment from 'moment'; // require
// This calss will be the game source.
// search for upcomming games
export default class GameSource { export default class GameSource {
async getGamesFromHaifa(logger: Function): Promise<GoogleCalendarEvent[]> {
console.log("Trying to get games from Haifa...");
async getGamesFromHaifa(): Promise<GoogleCalendarEvent[]> { try {
const sourceUrl = `https://mhaifafc.com/games?lang=en`; // Get the current date and time in the required format
const result = await axios.get(sourceUrl); const currentDate = moment().format("DD/MM/YYYY HH:mm");
const parsedResult = parse(result.data.toString())
const gameBoxs = parsedResult.querySelectorAll(".game-box"); // Construct the filters object with the current date
const filters = {
date: {
startDate: currentDate,
endDate: "",
},
league: "",
session: "",
gamesDirection: "1",
};
// Encode the filters for the URL
const filtersParam = encodeURIComponent(JSON.stringify(filters));
// Construct the API URL with the encoded filters
const sourceUrl = `https://api.mhaifafc.com/api/content/games-lobby?filters=${filtersParam}&start=0&limit=20&sortDirection=ASC&app=web&lang=he`;
// Get the authorization token from environment variables
const authorizationToken = process.env.HAIFA_API_AUTH_TOKEN;
// Set up the request headers
const headers = {
Accept: "*/*",
"Accept-Language": "en-US,en;q=0.7",
Authorization: `Bearer ${authorizationToken}`,
"User-Agent": "Mozilla/5.0",
Origin: "https://www.mhaifafc.com",
Referer: "https://www.mhaifafc.com/",
};
// Make the API request
const response = await axios.get(sourceUrl, {
headers,
responseType: "json", // Ensure the response is parsed as JSON
responseEncoding: "utf8", // Ensure UTF-8 encoding
});
// Extract the games data from the response
const gamesData = response.data.games.items;
const games: GoogleCalendarEvent[] = []; const games: GoogleCalendarEvent[] = [];
for (let gameBox of gameBoxs) { // Loop through each game and construct the GoogleCalendarEvent objects
for (const game of gamesData) {
const gameDetails = game.gameDetails;
const gameTime = gameDetails.gameTime; // ISO string
const isFinalGameDate = gameDetails.isFinalGameDate;
const gameLocation = gameDetails.gameLocation;
const teamsPlaying = gameBox.querySelectorAll(".team-name").map((team: any) => team.text); // Skip games without a game time
const regex = /[\r\n\s]+/g; if (!gameTime) continue;
const gameHeader = gameBox.querySelector(".game-header").text.replace(regex, " ").trim();
const headerSplit = gameHeader.split(",");
// In data, if there is no time, it means it's the last game for the calender
const lastGameForCalender = headerSplit.length < 4;
if (lastGameForCalender) break;
const gameDate = headerSplit[2].trim(); const hostTeam = game.hostTeam;
const gameTime = headerSplit[3].trim(); const guestTeam = game.guestTeam;
const startOriginal = moment(gameDate + gameTime, "DD/MM/YYYYHH:mm").format("DD/MM/YYYY HH:mm"); // Get team names
const endOriginal = moment(gameDate + gameTime, "DD/MM/YYYYHH:mm").add(2, "hours").format("DD/MM/YYYY HH:mm"); const hostTeamName = hostTeam.teamName;
const guestTeamName = guestTeam.teamName;
const start = [moment(startOriginal, 'DD/MM/YYYYHH:mm').year(), moment(startOriginal, 'DD/MM/YYYYHH:mm').month() + 1, moment(startOriginal, 'DD/MM/YYYYHH:mm').date(), moment(startOriginal, 'DD/MM/YYYYHH:mm').hour(), moment(startOriginal, 'DD/MM/YYYYHH:mm').minute()]; const summary = `${hostTeamName} vs. ${guestTeamName}`;
const end = [moment(endOriginal, 'DD/MM/YYYYHH:mm').year(), moment(endOriginal, 'DD/MM/YYYYHH:mm').month() + 1, moment(endOriginal, 'DD/MM/YYYYHH:mm').date(), moment(endOriginal, 'DD/MM/YYYYHH:mm').hour(), moment(endOriginal, 'DD/MM/YYYYHH:mm').minute()]
// Include a note if the game date is not final
let description = `${hostTeamName} vs. ${guestTeamName}`;
if (!isFinalGameDate) {
description += " (Date and time are subject to change)";
}
// Calculate start and end times
const startDateTime = moment(gameTime).toISOString();
const endDateTime = moment(gameTime).add(2, "hours").toISOString();
// Add the event to the games array
games.push({ games.push({
summary: 'Maccabi Haifa F.C.', summary: summary,
location: "Sammy Ofer Stadium", location: gameLocation,
description: `${teamsPlaying[0]} vs. ${teamsPlaying[1]}`, description: description,
start: { start: {
dateTime: start, dateTime: startDateTime,
timeZone: 'Asia/Jerusalem' timeZone: "Asia/Jerusalem",
}, },
end: { end: {
dateTime: end, dateTime: endDateTime,
timeZone: 'Asia/Jerusalem' timeZone: "Asia/Jerusalem",
} },
}) });
} }
return games; return games;
} } catch (error) {
console.error(error);
getOpponentIndexByStadium(stadium: string) { return [];
if (stadium === "Sammy Ofer Stadium") {
return 1;
} else {
return 0;
} }
} }
} }

View file

@ -1,65 +1,97 @@
import { JWT } from 'google-auth-library'; import { JWT } from "google-auth-library";
import { google } from 'googleapis'; import { google } from "googleapis";
import { GoogleCalendarEvent } from './types/index'; import { GoogleCalendarEvent } from "./types/index";
require('dotenv').config(); require("dotenv").config();
const env = process.env; const env = process.env;
export default class GoogleCalendar { export default class GoogleCalendar {
gamesMap: any = {};
clientSecret: string = env.GOOGLE_CLIENT_SECRET; clientSecret: string = env.GOOGLE_CLIENT_SECRET;
clientId: string = env.GOOGLE_CLIENT_ID; clientId: string = env.GOOGLE_CLIENT_ID;
calenderId: string = env.GOOGLE_CALENDAR_ID; calenderId: string = env.GOOGLE_CALENDAR_ID;
calendar: any; calendar: any;
clientEmail: string = env.GOOGLE_CLIENT_EMAIL; clientEmail: string = env.GOOGLE_CLIENT_EMAIL;
googlePrivateKey: string = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'); googlePrivateKey: string = env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, "\n");
token: any; token: any;
JWT_client: JWT; JWT_client: JWT;
async init() { async init() {
console.log("INIT GOOGLE CALENDAR") console.log("INIT GOOGLE CALENDAR");
const jwtClient = await this.authorize(); const jwtClient = await this.authorize();
this.calendar = google.calendar({ version: 'v3', auth: jwtClient }); this.calendar = google.calendar({ version: "v3", auth: jwtClient });
console.log("DONE INIT GOOGLE CALENDAR")
} }
async authorize() { async authorize() {
console.log("AUTHORIZE GOOGLE CALENDAR") console.log("AUTHORIZE GOOGLE CALENDAR");
this.JWT_client = new JWT({ this.JWT_client = new JWT({
email: this.clientEmail, email: this.clientEmail,
key: this.googlePrivateKey, key: this.googlePrivateKey,
scopes: [ scopes: ["https://www.googleapis.com/auth/calendar"],
'https://www.googleapis.com/auth/calendar',
]
}); });
const { access_token } = await this.JWT_client.authorize(); const { access_token } = await this.JWT_client.authorize();
this.token = access_token; this.token = access_token;
if (!this.token) { if (!this.token) {
throw new Error('Failed to connect to google calendar'); throw new Error("Failed to connect to google calendar");
} }
console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY") console.log("GOOGLE CALENDAR AUTHORIZED SUCCESSFULLY");
return this.JWT_client; return this.JWT_client;
} }
async updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) { async updateNewEvent(upcomingEvents: GoogleCalendarEvent[]) {
// console.log(upcomingEvents)
setTimeout(async () => { setTimeout(async () => {
upcomingEvents.forEach((event: GoogleCalendarEvent) => { upcomingEvents.forEach(async (event: GoogleCalendarEvent) => {
console.log("UPDATE NEW EVENT", upcomingEvents) console.log("UPDATE NEW EVENT", upcomingEvents);
const options = { const options = {
auth: this.JWT_client, auth: this.JWT_client,
calendarId: this.calenderId, calendarId: this.calenderId,
resource: event, resource: {
} summary: event.summary,
this.calendar.events.insert(options, function (err: any, event: any) { location: event.location,
description: event.description,
start: {
dateTime: event.start.dateTime,
timeZone: "Asia/Jerusalem",
},
end: { dateTime: event.end.dateTime, timeZone: "Asia/Jerusalem" },
sendNotifications: true,
},
};
await this.calendar.events.insert(
options,
function (err: any, event: any) {
if (err) { if (err) {
console.log('There was an error contacting the Calendar service: ' + err); console.log(
"There was an error contacting the Calendar service: " + err
);
return; return;
} }
console.log(event.description + ' created'); console.log(event.description + " created");
}
);
}); });
}, 3000);
}
}) async isDuplicateEvent(startTime: string, endTime: string, title: string) {
}, 3000) if (this.gamesMap[startTime]) {
console.log("duplicate event");
return true;
}
this.gamesMap[startTime] = true;
console.log("checking for duplicate event");
try {
const response = await this.calendar.events.list({
calendarId: this.calenderId,
timeMin: startTime,
timeMax: endTime,
q: title, // Search for events with the same title
});
return response.data.items.length > 0;
} catch (error) {
console.error(error.message);
return false;
}
} }
} }

View file

@ -1,44 +0,0 @@
import { GoogleCalendarEvent } from "./types";
import * as ics from 'ics';
const uuid = require('uuid').v4();
export default class Ics {
generateIcsOutputFromGames = (games: GoogleCalendarEvent[]) => {
let output = [];
games.forEach((game) => {
output.push(this.generateIcsOutputFromGame(game));
});
const { error, value } = ics.createEvents(output);
if (error) {
console.log(error);
return '';
}
return value;
}
generateIcsOutputFromGame = (game: GoogleCalendarEvent) => {
const { summary, location, description, start, end } = game;
const icsEvent: ics.EventAttributes = {
title: summary,
description,
location,
start: [start.dateTime[0], start.dateTime[1], start.dateTime[2], start.dateTime[3], start.dateTime[4]],
end: [end.dateTime[0], end.dateTime[1], end.dateTime[2], end.dateTime[3], end.dateTime[4]],
url: 'https://mhaifafc.com/',
status: 'CONFIRMED',
busyStatus: 'BUSY',
productId: 'https://mhaifafc.com/',
recurrenceRule: '',
attendees: [],
alarms: [],
categories: [],
organizer: { name: 'Maccabi Haifa F.C.', email: '' },
uid: uuid.toString(),
};
return icsEvent;
}
}

View file

@ -1,41 +1,74 @@
import GoogleCalendar from './GoogleCalendar'; import GameSource from "./GameSource";
import GameSource from './GameSource'; import GoogleCalendar from "./GoogleCalendar";
import fs from 'fs'; import env from "dotenv";
import Ics from './Ics'; import cron from 'node-cron';
import fs from 'fs'; // Importing fs for logging
env.config();
class App { class App {
googleCalendar: GoogleCalendar;
gameSource: GameSource; gameSource: GameSource;
ics: Ics;
googleToken: string; googleToken: string;
googleCalendar: GoogleCalendar;
constructor() { constructor() {
this.googleCalendar = new GoogleCalendar();
this.gameSource = new GameSource(); this.gameSource = new GameSource();
this.ics = new Ics(); this.googleCalendar = new GoogleCalendar();
} }
async init() { async startCronJob() {
console.log("INIT APP") this.writeLog('START Haifa Reminder'); // Log when the cron job starts
const newGamesAdded = [];
await this.googleCalendar.init(); await this.googleCalendar.init();
try {
const games = await this.gameSource.getGamesFromHaifa(this.writeLog);
for (const game of games) {
const isDuplicateEvent = await this.googleCalendar.isDuplicateEvent(
game.start.dateTime,
game.end.dateTime,
game.summary
);
console.log(game)
if (!isDuplicateEvent) {
newGamesAdded.push(game);
console.log("Event does not exist");
await this.googleCalendar.updateNewEvent([game]);
} else {
console.log("Event already exists");
}
} }
async getNewGamesAndUpdateCalendar() { if (newGamesAdded.length > 0) {
console.log("GET NEW GAMES AND UPDATE CALENDAR") console.log("New games added:", newGamesAdded);
const games = await this.gameSource.getGamesFromHaifa(); } else {
this.googleCalendar.updateNewEvent(games); console.log("No new games were Added!");
}
this.writeLog('Successfully ran project');
} catch (error) {
this.writeLog("Error in cron job:" + error.message);
} finally {
this.writeLog('END CRON JOB'); // Log when the cron job ends
}
}
writeLog(message) {
const timestamp = new Date().toISOString();
const logMessage = `${timestamp} - ${message}\n`;
// Write to log file synchronously
fs.appendFileSync('cron.log', logMessage);
console.log(logMessage); // Optional: also log to console
} }
} }
const app = new App(); const app = new App();
const start = async () => { cron.schedule('* * * * *', () => {
const outputFileLocation = 'maccabi-haifa-fc.ics'; console.log('Running startCronJob at 10:00 AM Jerusalem time');
const games = await app.gameSource.getGamesFromHaifa(); app.startCronJob().catch((error) => {
const icsEvents = app.ics.generateIcsOutputFromGames(games); console.error("Error in scheduled cron job:", error.message);
fs.writeFileSync(outputFileLocation, icsEvents); app.writeLog(`ERROR: ${error.message}`); // Log any errors
} });
}, {
start(); scheduled: true,
timezone: "Asia/Jerusalem"
});

View file

@ -3,11 +3,11 @@ export interface GoogleCalendarEvent {
location: string; location: string;
description: string; description: string;
start: { start: {
dateTime: number[]; dateTime: string;
timeZone: string; timeZone: string;
}; };
end: { end: {
dateTime: number[]; dateTime: string;
timeZone: string; timeZone: string;
}; };
} }

3
start.sh Normal file
View file

@ -0,0 +1,3 @@
#!/bin/bash
docker run -p 3000:3000 -d --restart=unless-stopped --name haifareminder docker.io/kfda89/haifareminder

View file

@ -5,7 +5,10 @@
"esModuleInterop": true, "esModuleInterop": true,
"target": "ES2019", "target": "ES2019",
"moduleResolution": "node", "moduleResolution": "node",
"outDir": "./public", "outDir": "./dist",
"rootDir": "./src" "rootDir": "./src"
} },
"include": [
"src/**/*"
]
} }