aboutsummaryrefslogtreecommitdiffstats
path: root/recipes/telegram/webview.js
blob: f05b43f341a0d9337102562b5463a65ce8ad3f8b (plain) (blame)
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
const _path = _interopRequireDefault(require('path'));

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}

module.exports = Ferdium => {
  const telegramVersion = document
    .querySelector('meta[name="application-name"]')
    ?.getAttribute('content');

  const isWebZ = telegramVersion?.includes('WebZ');
  const isWebK = telegramVersion?.includes('WebK');

  // There are two different Telegram versions for internal competition
  // Read more: https://bugs.telegram.org/c/4002/public
  const webZCount = () => {
    let directCount = 0;
    let groupCount = 0;

    const directCountSelector = document.querySelectorAll(
      '.chat-list .ListItem.private .Badge.unread:not(.muted)',
    );
    const groupCountSelector = document.querySelectorAll(
      '.chat-list .ListItem.group .Badge.unread:not(.muted)',
    );

    for (const badge of directCountSelector) {
      directCount += Ferdium.safeParseInt(badge.textContent);
    }

    for (const badge of groupCountSelector) {
      groupCount += Ferdium.safeParseInt(badge.textContent);
    }

    Ferdium.setBadge(directCount, groupCount);
  };

  const webKCount = () => {
    let directCount = 0;
    let groupCount = 0;

    const elements = document.querySelectorAll('.rp:not(.is-muted)');

    for (const element of elements) {
      const subtitleBadge = element.querySelector('.dialog-subtitle-badge');

      if (subtitleBadge) {
        const parsedValue = Ferdium.safeParseInt(subtitleBadge.textContent);

        if (element.dataset.peerId > 0) {
          directCount += parsedValue;
        } else {
          groupCount += parsedValue;
        }
      }
    }

    Ferdium.setBadge(directCount, groupCount);
  };

  const getMessages = () => {
    if (isWebZ) {
      webZCount();
    } else if (isWebK) {
      webKCount();
    }
  };

  const getActiveDialogTitle = () => {
    let element;

    if (isWebZ) {
      element = document.querySelector('.chat-list .ListItem .title > h3');
    } else if (isWebK) {
      element = document.querySelector('.top .peer-title');
    }

    Ferdium.setDialogTitle(element ? element.textContent : '');
  };

  const loopFunc = () => {
    getMessages();
    getActiveDialogTitle();
  };

  Ferdium.loop(loopFunc);

  Ferdium.injectCSS(_path.default.join(__dirname, 'service.css'));
};