Telegram Web K with changes to work inside I2P https://web.telegram.i2p/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

314 lines
10 KiB

3 years ago
/*
* https://github.com/morethanwords/tweb
* Copyright (C) 2019-2021 Eduard Kuzmenko
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*/
import { putPreloader } from "../components/putPreloader";
3 years ago
import Scrollable from '../components/scrollable';
import Page from "./page";
import InputField from "../components/inputField";
import CheckboxField from "../components/checkboxField";
import Button from "../components/button";
import fastSmoothScroll from "../helpers/fastSmoothScroll";
import IS_TOUCH_SUPPORTED from "../environment/touchSupport";
3 years ago
import App from "../config/app";
import I18n, { _i18n, i18n } from "../lib/langPack";
3 years ago
import lottieLoader from "../lib/rlottie/lottieLoader";
import ripple from "../components/ripple";
3 years ago
import findUpTag from "../helpers/dom/findUpTag";
import findUpClassName from "../helpers/dom/findUpClassName";
import { randomLong } from "../helpers/random";
import pageSignQR from "./pageSignQR";
import getLanguageChangeButton from "../components/languageChangeButton";
import cancelEvent from "../helpers/dom/cancelEvent";
3 years ago
import { attachClickEvent } from "../helpers/dom/clickEvent";
import replaceContent from "../helpers/dom/replaceContent";
import toggleDisability from "../helpers/dom/toggleDisability";
import sessionStorage from "../lib/sessionStorage";
import { DcAuthKey } from "../types";
import placeCaretAtEnd from "../helpers/dom/placeCaretAtEnd";
import { HelpCountry, HelpCountryCode } from "../layer";
import { getCountryEmoji } from "../vendor/emoji";
import simulateEvent from "../helpers/dom/dispatchEvent";
import stateStorage from "../lib/stateStorage";
3 years ago
import rootScope from "../lib/rootScope";
import TelInputField from "../components/telInputField";
import IS_EMOJI_SUPPORTED from "../environment/emojiSupport";
import setInnerHTML from "../helpers/dom/setInnerHTML";
3 years ago
import wrapEmojiText from "../lib/richTextProcessor/wrapEmojiText";
import apiManagerProxy from "../lib/mtproto/mtprotoworker";
2 years ago
import CountryInputField from "../components/countryInputField";
3 years ago
//import _countries from '../countries_pretty.json';
let btnNext: HTMLButtonElement = null, btnQr: HTMLButtonElement;
let onFirstMount = () => {
/* if(Modes.test) {
3 years ago
Countries.push({
_: 'help.country',
default_name: 'Test Country',
country_codes: [{
_: 'help.countryCode',
country_code: '999 66',
patterns: ['999 66 XXX XX']
}],
iso2: 'KK'
3 years ago
});
console.log('Added test country to list!');
} */
3 years ago
//const countries: Country[] = _countries.default.filter((c) => c.emoji);
// const countries: Country[] = Countries.filter((c) => c.emoji).sort((a, b) => a.name.localeCompare(b.name));
// const countries = I18n.countriesList.filter((country) => !country.pFlags?.hidden);
3 years ago
const inputWrapper = document.createElement('div');
inputWrapper.classList.add('input-wrapper');
2 years ago
let lastCountrySelected: HelpCountry, lastCountryCodeSelected: HelpCountryCode;
const countryInputField = new CountryInputField({
onCountryChange: (country, code) => {
lastCountrySelected = country, lastCountryCodeSelected = code;
3 years ago
2 years ago
if(!code) {
3 years ago
return;
}
2 years ago
telInputField.value = telInputField.lastValue = '+' + code.country_code;
setTimeout(() => {
telEl.focus();
placeCaretAtEnd(telEl, true);
}, 0);
3 years ago
}
});
const telInputField = new TelInputField({
onInput: (formatted) => {
lottieLoader.loadLottieWorkers();
3 years ago
const {country, code} = formatted || {};
let countryName = country ? country.name || country.default_name : ''/* 'Unknown' */;
if(countryName !== countryInputField.value && (
!lastCountrySelected ||
!country ||
!code || (
lastCountrySelected !== country &&
lastCountryCodeSelected.country_code !== code.country_code
)
)
) {
2 years ago
countryInputField.override(country, code, countryName);
}
//if(country && (telInputField.value.length - 1) >= (country.pattern ? country.pattern.length : 9)) {
if(country || (telInputField.value.length - 1) > 1) {
btnNext.style.visibility = '';
} else {
btnNext.style.visibility = 'hidden';
}
3 years ago
}
});
const telEl = telInputField.input;
3 years ago
telEl.addEventListener('keypress', (e) => {
3 years ago
//console.log('keypress', this.value);
3 years ago
if(!btnNext.style.visibility &&/* this.value.length >= 9 && */ e.key === 'Enter') {
3 years ago
return onSubmit();
}
});
/* telEl.addEventListener('focus', function(this: typeof telEl, e) {
this.removeAttribute('readonly'); // fix autocomplete
});*/
const signedCheckboxField = new CheckboxField({
text: 'Login.KeepSigned',
name: 'keepSession',
withRipple: true,
checked: true
});
signedCheckboxField.input.addEventListener('change', () => {
const keepSigned = signedCheckboxField.checked;
rootScope.managers.appStateManager.pushToState('keepSigned', keepSigned);
3 years ago
apiManagerProxy.toggleStorages(keepSigned, true);
3 years ago
});
apiManagerProxy.getState().then((state) => {
if(!stateStorage.isAvailable()) {
3 years ago
signedCheckboxField.checked = false;
signedCheckboxField.label.classList.add('checkbox-disabled');
} else {
signedCheckboxField.checked = state.keepSigned;
}
});
btnNext = Button('btn-primary btn-color-primary', {text: 'Login.Next'});
btnNext.style.visibility = 'hidden';
const onSubmit = (e?: Event) => {
if(e) {
cancelEvent(e);
}
const toggle = toggleDisability([/* telEl, countryInput, */btnNext, btnQr], true);
replaceContent(btnNext, i18n('PleaseWait'));
putPreloader(btnNext);
//return;
let phone_number = telInputField.value;
rootScope.managers.apiManager.invokeApi('auth.sendCode', {
3 years ago
phone_number: phone_number,
api_id: App.id,
api_hash: App.hash,
settings: {
_: 'codeSettings' // that's how we sending Type
}
//lang_code: navigator.language || 'en'
}).then((code) => {
//console.log('got code', code);
import('./pageAuthCode').then((m) => m.default.mount(Object.assign(code, {phone_number: phone_number})));
}).catch((err) => {
3 years ago
toggle();
switch(err.type) {
case 'PHONE_NUMBER_INVALID':
telInputField.setError();
replaceContent(telInputField.label, i18n('Login.PhoneLabelInvalid'));
telEl.classList.add('error');
replaceContent(btnNext, i18n('Login.Next'));
break;
default:
console.error('auth.sendCode error:', err);
btnNext.innerText = err.type;
break;
}
});
};
attachClickEvent(btnNext, onSubmit);
btnQr = Button('btn-primary btn-secondary btn-primary-transparent primary', {text: 'Login.QR.Login'});
let qrMounted = false;
btnQr.addEventListener('click', () => {
pageSignQR.mount();
/* const promise = import('./pageSignQR');
btnQr.disabled = true;
let preloaderDiv: HTMLElement;
if(!qrMounted) {
preloaderDiv = putPreloader(btnQr);
qrMounted = true;
}
promise.then((module) => {
3 years ago
module.default.mount();
setTimeout(() => {
btnQr.removeAttribute('disabled');
if(preloaderDiv) {
preloaderDiv.remove();
}
}, 200);
}); */
});
inputWrapper.append(countryInputField.container, telInputField.container, signedCheckboxField.label, btnNext, btnQr);
const h4 = document.createElement('h4');
h4.classList.add('text-center');
3 years ago
_i18n(h4, 'Login.Title');
const subtitle = document.createElement('div');
subtitle.classList.add('subtitle', 'text-center');
3 years ago
_i18n(subtitle, 'Login.StartText');
page.pageEl.querySelector('.container').append(h4, subtitle, inputWrapper);
let tryAgain = () => {
rootScope.managers.apiManager.invokeApi('help.getNearestDc').then((nearestDcResult) => {
const langPack = stateStorage.getFromCache('langPack');
if(langPack && !langPack.countries?.hash) {
I18n.getLangPack(langPack.lang_code).then(() => {
simulateEvent(telEl, 'input');
});
}
3 years ago
const dcs = new Set([1, 2, 3, 4, 5]);
const done: number[] = [nearestDcResult.this_dc];
let promise: Promise<any>;
if(nearestDcResult.nearest_dc !== nearestDcResult.this_dc) {
promise = rootScope.managers.apiManager.getNetworkerVoid(nearestDcResult.nearest_dc).then(() => {
3 years ago
done.push(nearestDcResult.nearest_dc);
});
}
(promise || Promise.resolve()).then(() => {
done.forEach((dcId) => {
3 years ago
dcs.delete(dcId);
});
const _dcs = [...dcs];
const g = async(): Promise<void> => {
const dcId = _dcs.shift();
if(!dcId) return;
const dbKey: DcAuthKey = `dc${dcId}_auth_key` as any;
const key = await sessionStorage.get(dbKey);
if(key) {
return g();
}
setTimeout(() => { // * если одновременно запросить все нетворкеры, не будет проходить запрос на код
rootScope.managers.apiManager.getNetworkerVoid(dcId/* , {fileDownload: true} */).finally(g);
3 years ago
}, /* done.includes(dcId) ? 0 : */3000);
};
g();
});
return nearestDcResult;
}).then((nearestDcResult) => {
if(!countryInputField.value.length && !telInputField.value.length) {
2 years ago
countryInputField.selectCountryByIso2(nearestDcResult.country);
3 years ago
}
//console.log('woohoo', nearestDcResult, country);
})//.catch(tryAgain);
};
if(!IS_TOUCH_SUPPORTED) {
3 years ago
setTimeout(() => {
telEl.focus();
}, 0);
}
getLanguageChangeButton(inputWrapper);
tryAgain();
};
const page = new Page('page-sign', true, onFirstMount, () => {
if(btnNext) {
replaceContent(btnNext, i18n('Login.Next'));
ripple(btnNext, undefined, undefined, true);
btnNext.removeAttribute('disabled');
}
if(btnQr) {
btnQr.removeAttribute('disabled');
}
rootScope.managers.appStateManager.pushToState('authState', {_: 'authStateSignIn'});
3 years ago
});
export default page;