How I Improved My User Experience with World Class Fitness Club

I have been going to the World Class fitness club for six months now, or as they write in the club itself, I am its resident. I chose this club mainly because it had a swimming pool. Then I became interested in group programs and often go to cycle training – this is training on a special exercise bike.

And the only thing that irritates me is that in order to view the schedule of classes for the next week, I had to go to the Word Class network website every time, go to my club, fight off several annoying banners that offer to call back in 3 seconds in order to become their client. And only after that find in the huge schedule a few lines that I am looking for. There can be several such classes during the week and I added them to my calendar so that I could go to at least one per week.
This whole operation with searching and entering into the calendar took about 15 minutes. And this happened every week.

At some point I got tired of this and thought, why not parse the schedule and add cycling classes to my calendar automatically?

One hurdle was that the World Class site dynamically loads content via JavaScript after the initial page load. But an API endpoint was found and now the cycling class is added to my calendar every Monday night in 3 seconds of scripting instead of 15 minutes of my life each week.

World Class Club Public Schedule Website

Usually the schedule greets you like this

Usually the schedule greets you like this

The site uses dynamic content loading using JavaScript. This means that a site that dynamically loads content using JavaScript after the initial page load is one where not all information is immediately available when the page first appears. Instead, additional data or content is retrieved from the server and displayed as the user interacts with the page. This technique is commonly used in modern web applications. It eliminates the need to reload the entire page and makes the experience faster and smoother for the user.

An API endpoint is a specific URL that allows external applications to interact with it. APIs allow different software systems to interact with each other by sending requests and receiving responses.

When interacting with a site that dynamically loads content, the site often requests data from its server using an API. The server processes the request and returns the required data, which is then displayed on the web page. In the context of World Class Fitness, the API endpoint would be a specific URL that provides class schedule data. By sending a request to this endpoint, you can retrieve the schedule data directly, bypassing the need to manually navigate the site.

The turning point and the technical problem

At some point I came across a clean link that leads only to the World Class fitness club schedule itself without any advertising. The link looks like this:

https://my.worldclass.ru/scheduling?clubs=d35ba5fc-1f7e-11ec-b664-50e548298f06

Where instead d35ba5fc-1f7e-11ec-b664-50e548298f06 there should be your club ID. Above is the club ID in the city of Perm.

All available IDs of other clubs can be viewed directly in the browser in page view mode:

List of available clubs

List of available clubs

Since World Class dynamically loads the schedule using JavaScript after the initial page load, it became a bit of a challenge to find the API endpoint and call it for this publicly available and freely published schedule on the internet.

ICG Color Cycle (cycle)

In the Perm club World Class it is not necessary to sign up for cycling classes in advance – it is enough to come about half an hour before the class and take a black card at the entrance to participate – there are places until the cards run out. True, sometimes those who signed up online come, but did not take a card – they simply did not know about it and there are not enough places. This is some confusion.

This is roughly what a cycle class looks like

This is roughly what a cycle class looks like

Creating a solution

Since I use Google Calendar, I wrote a Google Apps Script. Apps Script is a JavaScript-based platform for fast and easy development of solutions.

The script can significantly simplify the user's work, freeing him from the need to manually check the schedule and add classes to his Google calendar.

The script works as follows:

  1. Getting the schedule: The script sends a request to the World Class API with the ID of a specific gym. It then retrieves the schedule for the next seven days.

  2. Filtering relevant activities: after retrieving the schedule, the script filters out the “ICG Color Cycle” and “CORE” classes that I want to attend. All further actions occur only for the selected selection.

  3. Creating calendar events: for each filtered workout, the script automatically creates an event in the default Google calendar (you can specify any calendar, I have already written about working with calendars). Each event includes:

  • Name: name of the workout (in my case either “ICG Color Cycle” or “CORE”).

  • Duration: each event is scheduled for one hour.

  • Description: a detailed explanation of why this training is needed.

  • Location: the specific address of the World Class club where the class is held.

  • Logging and error handling: The script logs its progress, indicating when it starts and ends, and providing details about each event generated. If an API request fails or returns an error, the script logs an error message for troubleshooting.

File where you can see the token that you will need to access the API

File where you can see the token that you will need to access the API

In essence, this script is a time-saving tool for World Class club residents, who can be sure that they will always know when their favorite classes are held:

function WorldclassAPISchedulingPerm() {
    console.log(`Функция WorldclassAPISchedulingPerm начала работу в ${(new Date()).toLocaleString("ru-RU")}`);
  
    //https://habr.com/ru/articles/838322/

    const url="https://my.worldclass.ru/api/v1/clubs/scheduling";
    const currentDate = new Date();
    const endDate = new Date(currentDate);
    endDate.setDate(currentDate.getDate() + 7);

    const payload = {
        "gymList": [
            "d35ba5fc-1f7e-11ec-b664-50e548298f06" // это World Class в Перми
        ],
        "startDate": currentDate.toISOString().split('.')[0],
        "endDate": endDate.toISOString().split('.')[0],
        "chain": 1,
        "token": "70a69ca6-XXXX-XXXX-XXXX-005056b1372d" // здесь надо указать токен, узнать можно в DevTools Chrome на скриншоте выше 
    };

    const options = {
        method: 'post',
        contentType: 'application/json',
        payload: JSON.stringify(payload),
        muteHttpExceptions: true,
        headers: {
            'brand': 'WorldClass',
            'language': 'Ru',
            'chain': '1',
            'Accept': '*/*',
            'Origin': 'https://my.worldclass.ru',
            'Referer': 'https://my.worldclass.ru/scheduling?clubs="
        },
        timeoutSeconds: 30
    };

    try {
        const response = UrlFetchApp.fetch(url, options);
        const responseCode = response.getResponseCode();
        console.log(`Код ответа: ${responseCode}`);

        const responseText = response.getContentText();
        const responseData = JSON.parse(responseText); // Разбираем JSON-строку

        if (responseCode === 200) {
            // Фильтрация для "ICG Color Cycle (сайкл)" и "CORE"
            const filteredDates = responseData.data
                .filter(item => item.service.name === "ICG Color Cycle (сайкл)" || item.service.name === "CORE")
                .map(item => ({
                    name: item.service.name,
                    startDate: item.startDate
                }));

            console.log("Отфильтрованные даты:', filteredDates);

            // Создаем события в календаре для каждой отфильтрованной даты
            filteredDates.forEach(eventData => {
                const startTime = new Date(eventData.startDate);
                const endTime = new Date(startTime);
                endTime.setHours(startTime.getHours() + 1); // Устанавливаем продолжительность события на 1 час

                let eventTitle = eventData.name;
                let eventDescription = '';

                if (eventData.name === "ICG Color Cycle (сайкл)") {
                    eventDescription = 'ICG Color Cycle (сайкл тренировка с индивидуальными мониторами с мультимедийной системой ICG для визуализации данных и создания увлекательных программ. В зависимости от ваших данных мощности и сердечного ритма, которые фиксируются в режиме реального времени, для вас формируется оптимальная нагрузка в пяти цветовых зонах (белой, синей, зеленой, желтой и красной). Эти цвета зажигаются на передней панели – и отлично видны тренеру, который контролирует группу.';
                } else if (eventData.name === "CORE") {
                    eventDescription = 'CORE тренировка фокусируется на укреплении центральной части тела, включая мышцы брюшного пресса и поясницы. Занятие направлено на повышение стабильности и силы всего тела.';
                }

                CalendarApp.getDefaultCalendar().createEvent(
                    eventTitle,
                    startTime,
                    endTime, {
                        description: eventDescription,
                        location: 'Фитнес клуб World Class, Пермская ул., 33, Пермь, Пермский край, Россия, 614045'
                    }
                );

                console.log(`Событие создано для: ${startTime} - ${eventTitle}`);
            });

        } else {
            console.error(`Ошибка: получен статус ${responseCode} с ответом: ${responseText}`);
        }

    } catch (error) {
        console.error('Ошибка запроса:', error.message);
    }

    console.log(`Функция WorldclassAPISchedulingPerm закончила работу в ${(new Date()).toLocaleString("ru-RU")}`);
}
Result of script execution

Result of script execution

I don’t go to every class, I just look at the calendar and when there’s a window in my activity, I go to the nearest one.

How can you use this script?

If you are a beginner and want to automate getting certain lessons too, then Google Apps Script is a powerful tool that can help you:

Step 1: Access Google Apps Script

  1. Open Google Drive: start by going to Google Drive.

  2. Create a new script:

  • Click the button Create in the upper left corner.

  • Select More in the drop-down menu.

  • Click Google Apps Script. The Google Apps Script Editor will open in a new tab.

Step 2: Name your project

  1. Name your script: Once the Application Script Editor opens, you will see an untitled project. Click on the title (usually “Untitled Project”) and give it a meaningful name, such as “World Class Schedule”.

Step 3: Copy the code

  1. Remove default code: in the editor you will see the default code (function myFunction() {}). You can delete it to make room for the new script.

  2. Copy and paste the code:

  • Go to the article with the Google Apps Script code.

  • Copy the entire script provided in the article.

  • Go back to the Application Script Editor and paste the code into the blank space.

Step 4: Save your script

  1. Save your work: Click the floppy disk icon or press Ctrl + S (or Cmd + S on Mac) to save your script.

Step 5: Run the script

  1. Run your script: To test the script, click the play icon (▶) at the top of the editor. If this is your first time running the script, Google will ask for authorization.

  2. Authorize your script: Follow the instructions to allow the script to access your Google Calendar and other necessary services.

Step 6: Check the output

  1. Check the logs: After running the script, you can check the log messages to make sure it is working properly. Go to Просмотр > Журналы in the Application Script Editor to see the output.

Step 7: Automate it

  1. Set the trigger: If you want this script to run automatically at regular intervals, you can set up a trigger:

  • Click on the clock icon on the toolbar (Triggers).

  • Click + Add trigger in the lower right corner.

  • Set the script to run weekly, for example on the night between Monday and Tuesday.

And that's it! You've successfully created a Google Apps Script that automates adding a schedule to your Google Calendar.

Results

When using Google Calendar, this script is a handy tool that searches for interesting group events and adds them automatically to your own Google Calendar.

Author: Mikhail Shardin,

September 2, 2024

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *