phibr0 / obsidian-commander

Commander - Obsidian Plugin | Add Commands to every part of Obsidian's user interface
MIT License
733 stars 36 forks source link

[Bug]: Some time, startup command doesn't run #58

Open Mara-Li opened 1 year ago

Mara-Li commented 1 year ago

Describe the bug

I have a script that activate some plugins after the loading of Obsidian. This script is added to commands using the plugin User Plugin.

module.exports = {}

module.exports.onload = async (plugin) => {
    plugin.addCommand({
        id: 'List-plugins',
        name: 'Lister les plugins installés',
        checkCallback: async (checking) => {
            var plugins = Object.values(plugin.app.plugins.manifests).map(p => p.id).sort((a, b) => a.localeCompare(b));
            let written = [];
            const actualOpenedFile = plugin.app.workspace.getActiveFile();
            if (actualOpenedFile && actualOpenedFile.extension === 'md') {
                if (!checking) {
                    let contents = await plugin.app.vault.read(actualOpenedFile);
                    const listedPlugin = contents.split(/\r?\n/);
                    written = listedPlugin.map(p => p.slice(6));
                    let missingPlugin = plugins.filter(val => !written.includes(val)).filter(val => val.length > 0);
                    let removedPlugin = written.filter(val => !plugins.includes(val)).filter(val => val.length > 0);
                    let msg = 'Liste mise à jour ! ';
                    if (missingPlugin.length === 0 && removedPlugin.length === 0) {
                        msg = 'Liste triée par ordre alphabétique.';
                    }
                    if (removedPlugin.length > 0) {
                        removedPlugin.forEach(p => {
                            const replacer = new RegExp('\\- \\[.?\\] ' + p, "i");
                            contents = contents.replace(replacer, '');
                        });
                        msg += `${removedPlugin.length} plugin(s) supprimé(s) `;
                    }
                    contents = contents.split('\n')
                        .sort((a, b) => a.replace(/\- ((\[{2})|(\[.\]) )?/i, '')
                            .toLowerCase()
                            .localeCompare(b.replace(/\- ((\[{2})|(\[.\]) )?/i, '')
                                .toLowerCase()))
                        .join('\n');
                    if (missingPlugin.length > 0) {
                        contents = contents + '\n- [ ] ' + missingPlugin.join('\n- [ ] ');
                        msg += `${missingPlugin.length} plugin(s) ajouté(s)`;
                    }
                    await plugin.app.vault.modify(actualOpenedFile, contents.trim());
                    await new Notice(msg);
                }
                return true;
            }
            return false;
        }
    });

    async function fastStart(file, shortDelay, longDelay) {
        const contents = await plugin.app.vault.read(file);
        let allPlugins = contents.split(/r?\n/);
        let short = [];
        let long = [];
        let disable = [];
        for (let i = 0; i < allPlugins.length; i++) {
            if (allPlugins[i].startsWith('- [x]')) {
                short.push(allPlugins[i].slice(6, allPlugins.lenth))
            } else if (allPlugins[i].startsWith('- [>]')) {
                long.push(allPlugins[i].slice(6, allPlugins.lenth))
            } else if (allPlugins[i].startsWith('- [c]')) {
                disable.push(allPlugins[i].slice(6, allPlugins.lenth))
            }
        }
        setTimeout(async () => {
            short.forEach(async p => {
                await plugin.app.plugins.enablePlugin(p)
            }, shortDelay * 1000);
        });
        setTimeout(async () => {
            let i = 0;
            long.forEach(async p => {
                await plugin.app.plugins.enablePlugin(p)
                i++;
            }, longDelay * 1000);
        });

        disable.forEach(async p => {
            await plugin.app.plugins.disablePlugin(p)
        });
    }

    plugin.addCommand({
        id: 'Startup-script',
        name: 'Script de démarrage',
        callback: async () => {
            const findFile = plugin.app.vault.getFiles();
            try {
                if (!plugin.app.isMobile) {
                    new Notice('Démarrage en cours...');
                    const PCFile = findFile.find(f => f.name === 'PC.md');
                    console.log(`PC file found : ${PCFile.name}... LOADING....`);
                    await fastStart(PCFile, 2, 8);
                    console.log('PC file loaded!!');
                    new Notice('Plugins activés avec succès !')
                } else {
                    const MobileFile = findFile.find(f => f.name === 'Mobile.md');
                    await fastStart(MobileFile, 8, 15);
                }
            } catch (e) {
                new Notice(e)
            }
        }
    });
}

Some time, the script doesn't run... Only on PC. I tried to change the delay, but it seems that doesn't change anything.

Relevant errors (if available)

/

Steps to reproduce

  1. Register this plugin using User plugin
  2. Add an auto run macro with it
  3. Reload Obsidian

Expected Behavior

All my plugin start and I see some logging message in notice and console.

Additional context

Operating system

Windows