Skip to content

Commit

Permalink
Merge pull request #170 from soberhacker/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
soberhacker authored Jul 15, 2023
2 parents 572b6f6 + 57e14b9 commit 62c14f9
Show file tree
Hide file tree
Showing 13 changed files with 112 additions and 62 deletions.
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
# Changelog


## [1.8.1](https://github.com/soberhacker/obsidian-telegram-sync/compare/1.8.0...1.8.1) (2023-07-15)


### Bug Fixes

* connectiong as user ([c95e277](https://github.com/soberhacker/obsidian-telegram-sync/commit/c95e27771ede0af8dc47bac33d898d39282b06fe))
* missing bot restarting if no internet at run ([7387675](https://github.com/soberhacker/obsidian-telegram-sync/commit/73876756421a7aab545f91ac1840ebf8cc15fbee))
* undefined in the beginning of text ([3b75f18](https://github.com/soberhacker/obsidian-telegram-sync/commit/3b75f184116ec367981ef16df921c5439a029ef7))

## [1.8.0](https://github.com/soberhacker/obsidian-telegram-sync/compare/1.7.1...1.8.0) (2023-07-14)


Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "telegram-sync",
"name": "Telegram Sync",
"version": "1.8.0",
"version": "1.8.1",
"minAppVersion": "1.0.0",
"description": "Transfer messages and files from Telegram to Obsidian.",
"author": "soberhacker",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "obsidian-telegram-sync",
"version": "1.8.0",
"version": "1.8.1",
"description": "Transfer messages and files from Telegram bot to Obsidian.",
"main": "main.js",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion release-notes.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const version = "1.8.0";
export const version = "1.8.1";
// TODO add Demo gif and screenshots to readme.md
// TODO add thanks for last patrons in donation section
// TODO add notification about new version of Telegram Sync and link to the channel
Expand Down
30 changes: 18 additions & 12 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,18 @@ export default class TelegramSyncPlugin extends Plugin {

try {
// Check if the bot is connected and set the connected flag accordingly
this.botUser = await this.bot.getMe();
await this.bot.startPolling();
try {
this.botUser = await this.bot.getMe();
} finally {
await this.bot.startPolling();
}
this.botConnected = true;
} catch (e) {
displayAndLog(this, `${e}\n\nTelegram Bot is disconnected!`);
if (!this.bot || !this.bot.isPolling())
displayAndLog(
this,
`${e}\n\nTelegram Bot is disconnected.\n\nCheck internet(proxy) connection, the functionality of Telegram using the official app. If everithing is ok, restart Obsidian.`
);
}
}

Expand Down Expand Up @@ -158,7 +165,7 @@ export default class TelegramSyncPlugin extends Plugin {

if (
this.settings.telegramSessionType == "bot" ||
(this.settings.telegramSessionType == "user" && !this.userConnected)
(this.settings.telegramSessionType == "user" && !this.userConnected && sessionId)
) {
await GramJs.signInAsBot(this.settings.botToken);
}
Expand Down Expand Up @@ -187,13 +194,12 @@ export default class TelegramSyncPlugin extends Plugin {
}
}
}

async handlePollingError(error: unknown) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async handlePollingError(error: any) {
let pollingError = "unknown";

try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const errorCode = (error as any).response.body.error_code;
const errorCode = error.response.body.error_code;

if (errorCode === 409) {
pollingError = "twoBotInstances";
Expand All @@ -204,8 +210,7 @@ export default class TelegramSyncPlugin extends Plugin {
}
} catch {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
pollingError = (error as any).code === "EFATAL" ? "fatalError" : pollingError;
pollingError = error.code === "EFATAL" ? "fatalError" : pollingError;
} catch {
pollingError = "unknown";
}
Expand All @@ -215,7 +220,7 @@ export default class TelegramSyncPlugin extends Plugin {
this.lastPollingErrors.push(pollingError);
if (!(pollingError == "twoBotInstances")) {
this.botConnected = false;
await displayAndLogError(this, `${error} \n\nTelegram bot is disconnected!`);
await displayAndLogError(this, new Error(`${error} \n\nTelegram bot is disconnected!`));
}
}

Expand All @@ -229,7 +234,8 @@ export default class TelegramSyncPlugin extends Plugin {
}

async checkConnectionAfterError(intervalInSeconds = 30) {
if (this.checkingBotConnection || this.botConnected || !this.bot || !this.bot.isPolling()) return;
if (this.checkingBotConnection || !this.bot || !this.bot.isPolling()) return;
if (!this.checkingBotConnection && this.botConnected) this.lastPollingErrors = [];
try {
this.checkingBotConnection = true;
await new Promise((resolve) => setTimeout(resolve, intervalInSeconds * _1sec));
Expand Down
18 changes: 14 additions & 4 deletions src/settings/Settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import * as GramJs from "src/telegram/GramJs/client";
import { BotSettingsModal } from "./BotSettingsModal";
import { UserLogInModal } from "./UserLogInModal";
import { version } from "release-notes.mjs";
import { _5sec } from "src/utils/logUtils";
import { _15sec, _5sec, displayAndLog } from "src/utils/logUtils";

export interface TopicName {
name: string;
Expand All @@ -29,9 +29,9 @@ export interface TelegramSyncSettings {
pluginVersion: string;
appId: string;
apiHash: string;
topicNames: TopicName[];
telegramSessionType: GramJs.SessionType;
telegramSessionId: number;
topicNames: TopicName[];
}

export const DEFAULT_SETTINGS: TelegramSyncSettings = {
Expand All @@ -47,9 +47,9 @@ export const DEFAULT_SETTINGS: TelegramSyncSettings = {
// TODO Check for not public appId, apiHash how are often flood wait blocks and the level of downloading speed
appId: "17349", // public, ok to be here
apiHash: "344583e45741c457fe1862106095a5eb", // public, ok to be here
topicNames: [],
telegramSessionType: "bot",
telegramSessionId: GramJs.getNewSessionId(),
topicNames: [],
};

export class TelegramSyncSettingTab extends PluginSettingTab {
Expand Down Expand Up @@ -161,12 +161,22 @@ export class TelegramSyncSettingTab extends PluginSettingTab {
if (this.plugin.settings.telegramSessionType == "user") {
// Log Out
await this.plugin.initTelegramClient("bot");
displayAndLog(
this.plugin,
"Successfully logged out.\n\nBut you should also terminate the session manually in the Telegram app.",
_15sec
);
userStatusConstructor.call(this, userStatusComponent);
userLogInConstructor.call(this, userLogInButton);
} else {
// Log In
const initialSessionType = this.plugin.settings.telegramSessionType;
const userLogInModal = new UserLogInModal(this.plugin);
userLogInModal.onClose = async () => {
if (initialSessionType == "bot" && !this.plugin.userConnected) {
this.plugin.settings.telegramSessionType = initialSessionType;
this.plugin.saveSettings();
}
userStatusConstructor.call(this, userStatusComponent);
userLogInConstructor.call(this, userLogInButton);
};
Expand All @@ -180,7 +190,7 @@ export class TelegramSyncSettingTab extends PluginSettingTab {
.setDesc("Connect your telegram user. It's required only for ")
.addText(userStatusConstructor)
.addButton(userLogInConstructor);

// TODO removing Refresh button if this.plugin.settings.telegramSessionType changed to "bot" (when Log out, etc)
if (this.plugin.settings.telegramSessionType == "user" && !this.plugin.userConnected) {
userSettings.addExtraButton((refreshButton) => {
refreshButton.setTooltip("Refresh");
Expand Down
19 changes: 16 additions & 3 deletions src/settings/UserLogInModal.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Modal, Setting } from "obsidian";
import TelegramSyncPlugin from "src/main";
import * as GramJs from "src/telegram/GramJs/client";
import { _15sec, _5sec, displayAndLog, displayAndLogError } from "src/utils/logUtils";

export class UserLogInModal extends Modal {
botSetingsDiv: HTMLDivElement;
Expand Down Expand Up @@ -50,15 +49,16 @@ export class UserLogInModal extends Modal {
.addButton((b) => {
b.setButtonText("Generate QR code");
b.onClick(async () => {
await this.showQrCodeGeneratingState("🔵 QR code generating...\n", "#007BFF");
try {
await this.plugin.initTelegramClient("user");
await GramJs.signInAsUserWithQrCode(this.qrCodeContainer, this.password);
if (await GramJs.isAuthorizedAsUser()) {
this.plugin.userConnected = true;
displayAndLog(this.plugin, "Successfully logged in", _5sec);
await this.showQrCodeGeneratingState("🟢 Successfully logged in!\n", "#008000");
}
} catch (e) {
await displayAndLogError(this.plugin, e, undefined, _15sec);
await this.showQrCodeGeneratingState(`🔴 ${e}\n`, "#FF0000");
}
});
});
Expand Down Expand Up @@ -86,6 +86,19 @@ export class UserLogInModal extends Modal {
onOpen() {
this.display();
}

cleanQrContainer() {
while (this.qrCodeContainer.firstChild) {
this.qrCodeContainer.removeChild(this.qrCodeContainer.firstChild);
}
}

async showQrCodeGeneratingState(text: string, color?: string) {
this.cleanQrContainer();
const message = this.qrCodeContainer.createEl("pre", { text });
if (color) message.style.color = color;
message.style.fontWeight = "bold";
}
}

// addClientAuthorizationDescription() {
Expand Down
16 changes: 12 additions & 4 deletions src/telegram/GramJs/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,14 @@ export function getNewSessionId(): number {

// Stop the bot polling
export async function stop() {
if (client) {
await client.destroy();
try {
if (client) {
client.setLogLevel(LogLevel.NONE);
await client.destroy();
}
} catch {
/* empty */
} finally {
client = undefined;
_botToken = undefined;
_voiceTranscripts = undefined;
Expand Down Expand Up @@ -81,7 +87,8 @@ export async function init(
const authorized = await client.checkAuthorization();
if (sessionType == "user" && authorized && (await client.isBot()))
throw new Error("Stored session conflict. Try to log in again.");
if (!_clientUser && authorized) _clientUser = (await client.getMe()) as Api.User;
if (!authorized) _clientUser = undefined;
else if (!_clientUser && authorized) _clientUser = (await client.getMe()) as Api.User;
} catch (e) {
if (sessionType == "user") {
await init(_sessionId, "bot", apiId, apiHash, deviceId);
Expand Down Expand Up @@ -134,7 +141,8 @@ export async function signInAsBot(botToken: string) {

export async function signInAsUserWithQrCode(container: HTMLDivElement, password?: string) {
if (!client) throw NotConnected;
if ((await client.checkAuthorization()) && (await client.isBot())) new Error("User session is missed");
if ((await client.checkAuthorization()) && (await client.isBot()))
throw new Error("User session is missed. Try to restart the plugin or Obsidian");
await client
.signInUserWithQrCode(
{ apiId: _apiId, apiHash: _apiHash },
Expand Down
22 changes: 13 additions & 9 deletions src/telegram/message/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import TelegramSyncPlugin from "../../main";
import TelegramBot from "node-telegram-bot-api";
import { createFolderIfNotExist, getUniqueFilePath } from "src/utils/fsUtils";
import { createFolderIfNotExist, getTelegramMdPath, getUniqueFilePath } from "src/utils/fsUtils";
import * as release from "../../../release-notes.mjs";
import { buyMeACoffeeLink, boostyLink, kofiLink, paypalLink } from "../../settings/donation";
import { SendMessageOptions } from "node-telegram-bot-api";
import path from "path";
import * as GramJs from "../GramJs/client";
import { extension } from "mime-types";
import { applyNoteContentTemplate, finalizeMessageProcessing, getTelegramMdPath } from "./processors";
import { applyNoteContentTemplate, finalizeMessageProcessing } from "./processors";
import { ProgressBarType, createProgressBar, deleteProgressBar, updateProgressBar } from "../progressBar";
import { getFileObject } from "./getters";
import { TFile } from "obsidian";
Expand Down Expand Up @@ -79,9 +79,8 @@ async function createNoteContent(
plugin: TelegramSyncPlugin,
filePath: string,
notePath: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error: any,
msg: TelegramBot.Message
msg: TelegramBot.Message,
error?: Error
) {
let fileLink: string;

Expand All @@ -103,8 +102,7 @@ export async function handleFiles(plugin: TelegramSyncPlugin, msg: TelegramBot.M
await createFolderIfNotExist(plugin.app.vault, basePath);
let filePath = "";
let telegramFileName = "";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let error: any;
let error: Error | undefined = undefined;

try {
// Iterate through each file type
Expand Down Expand Up @@ -188,7 +186,13 @@ export async function handleFiles(plugin: TelegramSyncPlugin, msg: TelegramBot.M
}

if (plugin.settings.appendAllToTelegramMd) {
const noteContent = await createNoteContent(plugin, filePath, getTelegramMdPath(plugin), error, msg);
const noteContent = await createNoteContent(
plugin,
filePath,
getTelegramMdPath(plugin.app.vault, plugin.settings.newNotesLocation),
msg,
error
);
plugin.messageQueueToTelegramMd.push({ msg, formattedContent: noteContent, error });
return;
} else if (msg.caption || telegramFileName) {
Expand All @@ -202,7 +206,7 @@ export async function handleFiles(plugin: TelegramSyncPlugin, msg: TelegramBot.M
msg.date
);

const noteContent = await createNoteContent(plugin, filePath, notePath, error, msg);
const noteContent = await createNoteContent(plugin, filePath, notePath, msg, error);
await plugin.app.vault.create(notePath, noteContent);
}

Expand Down
Loading

0 comments on commit 62c14f9

Please sign in to comment.