Skip to content

Instantly share code, notes, and snippets.

@ALTaww
Last active April 27, 2024 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ALTaww/c37765362b71b0d87beb8ab17706de77 to your computer and use it in GitHub Desktop.
Save ALTaww/c37765362b71b0d87beb8ab17706de77 to your computer and use it in GitHub Desktop.
Скрипт показывает уведомление о новой версии скрипта в github gist

Использование:

  1. В блоке ==UserScript== добавить данный @require
// @require      https://gist.githubusercontent.com/ALTaww/c37765362b71b0d87beb8ab17706de77/raw/newScriptVersion.js
  1. Иницилизировать и вызвать функцию класса.
let newVersionChecker = new newScriptVersion('GITHUB_NICK', 'SCRIPTS_NAME', 'SCRIPTS_URL_PART', 'SCRIPTS_FILENAME');
newVersionChecker.checkNewVersion();

Инициализация

constructor(githubNick, scriptsName, scriptUrlPart, scriptsFilename)

githubNick (обязательное) - Ваш никнейм на гитхабе, будет использоваться для ссылки.

scriptsName (обязательное) - Имя скрипта, будет показываться в уведомлении, а также сохранено в localStorage.

scriptUrlPart (обязательное) - Часть ссылки скрипта между слэшами (/) сразу после никнейма.

scriptsFilename (обязательное) - Полное название файла (часть после последнего слэша).

Примечание: если вы хотите чтобы при нажатии на ссылку скрипта у пользователя автоматически открывался Tampermonkey, название должно содержать user. см. Пример использования.

Пример использования

let newVersionChecker = new newScriptVersion('ALTaww', 'Shiki Auto Watched Dates', 'fca3cc25c0ad3bdaee2b7d8cc19d4696', 'dates.user.js');
newVersionChecker.checkNewVersion();
class newScriptVersion {
constructor(githubNick, scriptsName, scriptUrlPart, scriptsFilename) {
this.githubNick = githubNick;
this.scriptsName = scriptsName;
this.scriptsUrlPart = scriptUrlPart;
this.scriptsFilename = scriptsFilename;
}
async checkNewVersion(time = new Date().getTime()) {
if (!localStorage.getItem(`scriptsCheckedTime`)) {
localStorage.setItem(`scriptsCheckedTime`, '{}');
}
let scriptsCheckedTime = JSON.parse(localStorage.getItem('scriptsCheckedTime')) || {};
let checkedTime = scriptsCheckedTime[this.scriptsName] || 0;
if (!checkedTime) {
scriptsCheckedTime[this.scriptsName] = time;
localStorage.setItem('scriptsCheckedTime', JSON.stringify(scriptsCheckedTime));
return;
}
// Проверка раз в день
if (+checkedTime + 86_400_000 > time) return;
try {
let gist = await fetch(`https://api.github.com/gists/${this.scriptsUrlPart}`);
let body = await gist.json();
let scriptUpdatedAt = new Date(body.updated_at).getTime();
if (+checkedTime < scriptUpdatedAt) {
this.showNotification(time, scriptsCheckedTime);
}
} catch (err) {
console.log(err);
}
}
showNotification(time, scriptsCheckedTime) {
let notification = document.createElement('div');
notification.className = 'newScriptVersion';
let innerText = document.createElement('p');
let link = document.createElement('a');
let dontShow = document.createElement('p');
let removeNotification = document.createElement('span');
let ignoreThisVersion = document.createElement('p');
innerText.innerText = `Доступна новая версия скрипта ${this.scriptsName}`
link.href = `https://gist.githubusercontent.com/${this.githubNick}/${this.scriptsUrlPart}/raw/${this.scriptsFilename}`;
link.innerText = 'Переустановить';
dontShow.classList = "dont-show";
dontShow.innerText = "Не уведомлять об обновлениях этого скрипта";
removeNotification.classList = 'remove-notification';
removeNotification.innerText = 'X';
ignoreThisVersion.innerText = 'Игнорировать эту версию';
ignoreThisVersion.classList = 'ignore-script-version';
let affirm = document.createElement('p');
affirm.classList = 'affirm';
affirm.innerText = `Вы уверены? Уведомления об обновлениях данного`;
affirm.innerText += '\nскрипта больше не будут показываться.'
notification.append(removeNotification, innerText, link, ignoreThisVersion, dontShow, affirm);
document.body.append(notification);
this.insertStyle()
notification.addEventListener('click', NotificationClicked);
let scriptsName = this.scriptsName;
function NotificationClicked(event) {
if (event.target === removeNotification) {
notification.remove();
return;
}
if (event.target === link || event.target === ignoreThisVersion) {
scriptsCheckedTime[scriptsName] = time;
localStorage.setItem('scriptsCheckedTime', JSON.stringify(scriptsCheckedTime));
notification.remove();
return;
}
if (event.target === dontShow) {
dontShow.style.opacity = 0;
affirm.style.display = 'block';
return;
}
if (event.target === affirm) {
scriptsCheckedTime[scriptsName] = time + 10**99;
localStorage.setItem('scriptsCheckedTime', JSON.stringify(scriptsCheckedTime));
notification.remove();
return;
}
}
}
insertStyle() {
let style, css;
css = `
.newScriptVersion {
position: fixed;
background: white;
color: black !important;
right: 8px;
top: 52px;
z-index: 99;
border-radius: 12px;
border: 1px solid black;
max-width: 100%;
}
.newScriptVersion > * {
margin: 10px;
}
.newScriptVersion p,
.newScriptVersion div{
display: flex;
color: black;
}
.newScriptVersion a {
color: #001dff !important;
}
.newScriptVersion a:hover,
.newScriptVersion .remove-notification:hover,
.newScriptVersion .ignore-script-version:hover,
.newScriptVersion .dont-show:hover,
.newScriptVersion .affirm:hover {
color: #ff8e00 !important;
}
.newScriptVersion .affirm {
display: none;
color: red;
}
.newScriptVersion .dont-show {
color: red;
}
.newScriptVersion .remove-notification {
float: right;
}
.newScriptVersion .remove-notification,
.newScriptVersion .dont-show,
.newScriptVersion .affirm,
.newScriptVersion .ignore-script-version {
cursor: pointer;
}
.newScriptVersion .ignore-script-version {
color: #176093;
}
`;
style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment