obsidian#moment TypeScript Examples

The following examples show how to use obsidian#moment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: main.ts    From obsidian-custom-attachment-location with GNU General Public License v3.0 6 votes vote down vote up
getPastedImageFileName(mdFileName: string)
    {
        let datetime = moment().format(this.settings.dateTimeFormat);
        let name = new TemplateString(this.settings.pastedImageFileName).interpolate({
            filename: mdFileName,
            date: datetime
        });
        return name;
    }
Example #2
Source File: i18n.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
_get(key: TransItemType) {
    let realLang = this.lang;
    if (this.lang === "auto" && moment.locale().replace("-", "_") in LANGS) {
      realLang = moment.locale().replace("-", "_") as LangType;
    } else {
      realLang = "en";
    }

    const res: string =
      (LANGS[realLang] as typeof LANGS["en"])[key] || LANGS["en"][key] || key;
    return res;
  }
Example #3
Source File: helpers.ts    From obsidian-spaced-repetition with MIT License 6 votes vote down vote up
export function t(str: keyof typeof en, params?: Record<string, unknown>): string {
    if (!locale) {
        console.error(`SRS error: Locale ${moment.locale()} not found.`);
    }

    const result = (locale && locale[str]) || en[str];

    if (params) {
        return interpolate(result, params);
    }

    return result;
}
Example #4
Source File: api.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
async getHighlights(lastSyncDate?: Date, limit = 2000) {
    let annotations = [];

    try {
      // Paginate API calls via search_after param
      // search_after=null starts at with the earliest annotations
      let newestTimestamp = lastSyncDate && moment.utc(lastSyncDate).format()
      while (annotations.length < limit) {
        const response = await axios.get(
          `${this.baseUrl}/search`,
          {
            params: {
              limit: 200, // Max pagination size
              sort: "updated",
              order: "asc", // Get all annotations since search_after
              search_after: newestTimestamp,
              user: this.userid,
            },
            headers: this.getHeaders()
          }
        )
        const newAnnotations = response.data.rows;
        if (!newAnnotations.length) {
          // No more annotations
          break;
        }

        annotations = [ ...annotations, ...newAnnotations ];
        newestTimestamp = newAnnotations[newAnnotations.length - 1].updated;
      }

    } catch (e) {
      new Notice('Failed to fetch Hypothes.is annotations. Please check your API token and try again.')
      console.error(e);
    }

    return annotations;
  }
Example #5
Source File: parseSyncResponse.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
parseHighlight = (annotationData, groupName: string, momentFormat: string): Highlights => {
    try {
        // Get highlighted text or reply
        let isReply, highlightText = null;
        const selector = annotationData['target'][0]['selector']
        if (selector) {
            highlightText = selector
                .find(item => item.type === "TextQuoteSelector")
                ?.exact
        } else {
            // Could be page note or reply
            if (annotationData['references']) {
                isReply = true
            }
        }

        return {
            id: annotationData['id'],
            created: moment(annotationData['created']).format(momentFormat),
            updated: moment(annotationData['updated']).format(momentFormat),
            text: highlightText && cleanTextSelectorHighlight(highlightText),
            incontext: annotationData['links']['incontext'],
            user: annotationData['user'],
            annotation: annotationData['text'],
            tags: annotationData['tags'],
            group: groupName,
            isReply,
        }
    } catch (error) {

        console.log(`Error parsing annotation format: ${error}`, annotationData);
        return null
    }
}
Example #6
Source File: Parser.ts    From obsidian-ReadItLater with MIT License 5 votes vote down vote up
protected getFormattedDateForFilename(): string {
        const date = new Date();
        return moment(date).format('YYYY-MM-DD HH-mm-ss');
    }
Example #7
Source File: ArticleSuggestModal.ts    From obsidian-rss with GNU General Public License v3.0 5 votes vote down vote up
renderSuggestion(item: RssFeedItem, el: HTMLElement) : void {
        el.createEl("div", { text: item.title });
        el.createEl("small", { text: moment(item.pubDate).format(this.plugin.settings.dateFormat) + " " + item.creator });
    }
Example #8
Source File: helpers.ts    From obsidian-dictionary with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function t(str: keyof typeof en): string {
    if (!locale) {
        console.error("Error: dictionary locale not found", moment.locale());
    }

    return (locale && locale[str]) || en[str];
}
Example #9
Source File: helpers.ts    From obsidian-dictionary with GNU Affero General Public License v3.0 5 votes vote down vote up
locale = localeMap[moment.locale()]
Example #10
Source File: helpers.ts    From obsidian-spaced-repetition with MIT License 5 votes vote down vote up
locale = localeMap[moment.locale()]
Example #11
Source File: helpers.ts    From obsidian-admonition with MIT License 5 votes vote down vote up
locale = localeMap[moment.locale()]
Example #12
Source File: functions.ts    From obsidian-rss with GNU General Public License v3.0 4 votes vote down vote up
function applyTemplate(plugin: RssReaderPlugin, item: RssFeedItem, template: string, filename?: string): string {
    let result = template.replace(/{{title}}/g, item.title);
    result = result.replace(/{{link}}/g, item.link);
    result = result.replace(/{{author}}/g, item.creator);
    result = result.replace(/{{published}}/g, moment(item.pubDate).format(plugin.settings.dateFormat));
    result = result.replace(/{{created}}/g, moment().format(plugin.settings.dateFormat));
    result = result.replace(/{{date}}/g, moment().format(plugin.settings.dateFormat));
    result = result.replace(/{{feed}}/g, item.feed);
    result = result.replace(/{{folder}}/g, item.folder);
    result = result.replace(/{{description}}/g, item.description);
    result = result.replace(/{{media}}/g, item.enclosure);

    result = result.replace(/({{published:).*(}})/g, function (k) {
        const value = k.split(":")[1];
        const format = value.substring(0, value.indexOf("}"));
        return moment(item.pubDate).format(format);
    });

    result = result.replace(/({{created:).*(}})/g, function (k) {
        const value = k.split(":")[1];
        const format = value.substring(0, value.indexOf("}"));
        return moment().format(format);
    });

    result = result.replace(/({{tags:).*(}})/g, function (k) {
        const value = k.split(":")[1];
        const separator = value.substring(0, value.indexOf("}"));
        return item.tags.join(separator);
    });

    result = result.replace(/({{#tags:).*(}})/g, function (k) {
        const value = k.split(":")[1];
        const separator = value.substring(0, value.indexOf("}"));
        return item.tags.map(i => '#' + i).join(separator);
    });

    result = result.replace(/{{tags}}/g, item.tags.join(", "));
    result = result.replace(/{{#tags}}/g, item.tags.map(i => '#' + i).join(", "));



    result = result.replace(/{{highlights}}/g, item.highlights.map(value => {
        //remove wallabag.xml - from the start of a highlight
        return "- " + rssToMd(plugin, removeFormatting(value).replace(/^(-+)/, ""))
    }).join("\n"));

    result = result.replace(/({{highlights:)[\s\S][^}]*(}})/g, function (k) {
        const value = k.split(/(:[\s\S]?)/);
        const tmp = value.slice(1).join("");
        const template = tmp.substring(1, tmp.indexOf("}"));
        return item.highlights.map(i => {
            return template.replace(/%%highlight%%/g, rssToMd(plugin, removeFormatting(i)).replace(/^(-+)/, ""));
        }).join("");
    });

    if (filename) {
        result = result.replace(/{{filename}}/g, filename);
    }

    let content = rssToMd(plugin, item.content);


    item.highlights.forEach(highlight => {
        const mdHighlight = htmlToMarkdown(highlight);
        content = content.replace(mdHighlight, "==" + mdHighlight + "==");
    });


    /*
    fixes #48
    replacing $ with $$$, because that is a special regex character:
    https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/string/replace#specifying_a_string_as_a_parameter
    solution taken from: https://stackoverflow.com/a/22612228/5589264
    */
    content = content.replace(/\$/g, "$$$");


    result = result.replace(/{{content}}/g, content);

    return result;
}
Example #13
Source File: CleanupModal.ts    From obsidian-rss with GNU General Public License v3.0 4 votes vote down vote up
async onOpen() : Promise<void> {
        const {contentEl} = this;

        contentEl.empty();

        contentEl.createEl("h1", {text: t("cleanup")});
        contentEl.createEl("p", {text: t("cleanup_help")});
        contentEl.createEl("p", {text: t("cleanup_help2")});

        new Setting(contentEl)
            .setName(t("unread"))
            .addToggle(toggle => {
                toggle.onChange((value) => {
                    this.unread = value;
                })
            });

        new Setting(contentEl)
            .setName(t("read"))
            .addToggle(toggle => {
                toggle.onChange((value) => {
                    this.read = value;
                })
            });

        new Setting(contentEl)
            .setName(t("favorite"))
            .addToggle(toggle => {
                toggle.onChange((value) => {
                    this.favorite = value;
                })
            });

        new Setting(contentEl)
            .setName(t("tag"))
            .addSearch(search => {
                const tags: string[] = [];
                for (const feed of this.plugin.settings.items) {
                    for(const item of feed.items) {
                        if(item !== undefined)
                            tags.push(...item.tags);
                    }
                }
                new ArraySuggest(this.app, search.inputEl, new Set<string>(tags));
                search
                    .onChange(async (value: string) => {
                        this.tag = value;
                    });
            });

        let older_than_setting: TextComponent;
        new Setting(contentEl)
            .setName(t("older_than"))
            .setDesc(t("older_than_help"))
            .addText(text => {
                older_than_setting = text;
                text.setPlaceholder("5")
                    .onChange(value => {
                        this.removeValidationError(text);
                        if (Number(value)) {
                            this.older_than = Number(value);
                        }
                    });

            }).controlEl.addClass("rss-setting-input");
        //we don't want decimal numbers.
        older_than_setting.inputEl.setAttr("onkeypress", "return event.charCode >= 48 && event.charCode <= 57");

        new Setting(contentEl)
            .setName(t("from_feed"))
            .addDropdown(dropdown => {
                dropdown.addOption("wallabag.xml-option-id", t("all"));

                const sorted = sortBy(groupBy(this.plugin.settings.feeds, "folder"), function (o) {
                    return o[0].folder;
                });
                for (const [, feeds] of Object.entries(sorted)) {
                    for (const id in feeds) {
                        const feed = feeds[id];
                        dropdown.addOption(feed.folder + "-" + feed.name, feed.folder + " - " + feed.name);
                    }
                    dropdown.setValue(this.feed);
                }
                dropdown.onChange(value => {
                    this.feed = value;
                });
            });

        const details = contentEl.createEl("details");
        const summary = details.createEl("summary");
        summary.setText(t("advanced"));
        const advanced = details.createDiv("advanced");

        new Setting(advanced)
            .setName(t("remove_wrong_feed"))
            .setDesc(t("remove_wrong_feed_help"))
            .addToggle(toggle => {
                toggle.onChange((value) => {
                    this.wrong_feed = value;
                })
            });

        new Setting(contentEl).addButton((button) => {
            button
                .setIcon("feather-trash")
                .setTooltip(t("perform_cleanup"))
                .onClick(async () => {

                    let items: RssFeedContent[] = this.plugin.settings.items;

                    let date = moment();
                    if (this.older_than) {
                        date = moment().subtract(this.older_than, 'days');
                    }

                    let count = 0;
                    const itemsCount = items.reduce((count, current) => count + current.items.length, 0);
                    const notice = new Notice(t("scanning_items", "0", itemsCount.toString()));

                    for(const feed of items) {
                        for (const item of feed.items) {
                            if (item !== undefined) {
                                let toRemove = 0;
                                if (item.pubDate === undefined || moment(item.pubDate).isBefore(date)) {
                                    if (this.feed === "wallabag.xml-option-id" || this.feed === (item.folder + "-" + item.feed)) {
                                        if ((this.read && item.read) || (!this.read && !item.read) || (this.read && !item.read)) {
                                            toRemove++;
                                        }
                                        if ((this.unread && !item.read) || (!this.unread && item.read)) {
                                            toRemove++;
                                        }
                                        if ((this.favorite && item.favorite) || (!this.favorite && !item.favorite) || (this.favorite && !item.favorite)) {
                                            toRemove++;
                                        }
                                        if (this.tag === "" || item.tags.includes(this.tag)) {
                                            toRemove++;
                                        }
                                    }

                                }
                                if(toRemove == 4) {
                                    feed.items = feed.items.filter(value => value.hash !== item.hash);
                                }
                            }

                            count++;
                            notice.setMessage(t("scanning_items", count.toString(), itemsCount.toString()));
                        }
                    }

                    if (this.wrong_feed) {
                        console.log("removing invalid feeds");
                        const feeds = this.plugin.settings.feeds.map<string>((feed) => {
                            return feed.name;
                        });
                        items = items.filter((item) => {
                            return feeds.includes(item.name);
                        });

                        const folders = get(folderStore);
                        items = items.filter((item) => {
                            return folders.has(item.folder);
                        });

                        //removing wallabag.xml items that do not fit
                        items.forEach((feed) => {
                            feed.items = feed.items.filter((item) => {
                                return feed.name === item.feed && feed.folder === item.folder;
                            });
                        });
                    }

                    await this.plugin.writeFeedContent(() => {
                        return items;
                    });
                    this.close();

                });
        }).addExtraButton((button) => {
            button
                .setIcon("cross")
                .setTooltip(t("cancel"))
                .onClick(() => {
                    this.close();
                })
        });
    }
Example #14
Source File: FeedSettings.ts    From obsidian-rss with GNU General Public License v3.0 4 votes vote down vote up
function displayFeedList(plugin: RssReaderPlugin, container: HTMLElement, disabled = false) {

    container.empty();

    const sorted = sortBy(groupBy(plugin.settings.feeds, "folder"), function (o) {
        return o[0].folder;
    });
    for (const [, feeds] of Object.entries(sorted)) {
        for (const id in feeds) {
            const feed = feeds[id];

            const setting = new Setting(container);

            setting.setName((feed.folder ? feed.folder : t("no_folder")) + " - " + feed.name);
            setting.setDesc(feed.url);

            setting
                .addExtraButton((b) => {
                    b
                        .setDisabled(disabled)
                        .setIcon("edit")
                        .setTooltip(t("edit"))
                        .onClick(() => {
                            const modal = new FeedModal(plugin, feed);
                            const oldFeed: RssFeed = feed;

                            modal.onClose = async () => {
                                if (modal.saved) {
                                    const feeds = plugin.settings.feeds;
                                    feeds.remove(oldFeed);
                                    feeds.push({
                                        name: modal.name,
                                        url: modal.url,
                                        folder: modal.folder ? modal.folder : ""
                                    });

                                    let items = plugin.settings.items;

                                    //make sure this data is transferred to the new entry, or this will cause a lot
                                    //of chaos when renaming, like putting entries into the wrong feed.
                                    items = items.filter((content) => {
                                        return content.name === oldFeed.name && content.folder === oldFeed.folder;
                                    });
                                    items.forEach((content) => {
                                        content.name = modal.name;
                                        content.folder = modal.folder;
                                        content.hash = <string>new Md5().appendStr(modal.name).appendStr(modal.folder).end();
                                        content.items.forEach(item => {
                                            item.feed = modal.name;
                                            item.folder = modal.folder ? modal.folder : "";
                                            item.hash = <string>new Md5().appendStr(item.title).appendStr(item.folder).appendStr(item.link).end();
                                        });
                                    });
                                    await plugin.writeFeedContent(() => {
                                        return items;
                                    });

                                    await plugin.writeFeeds(() => (feeds));
                                    displayFeedList(plugin, container);
                                }
                            };

                            modal.open();
                        });
                })
                .addExtraButton((button) => {
                    button
                        .setDisabled(disabled)
                        .setTooltip(t("from_archive"))
                        .setIcon("archive")
                        .onClick(async () => {
                            const modal = new MessageModal(plugin, t("reading_archive"));
                            modal.open();
                            displayFeedList(plugin, container, true);

                            const timemap = await request({
                                method: "GET",
                                url: "https://web.archive.org/web/timemap/link/" + feed.url
                            });
                            const items: RssFeedContent[] = [];
                            const lines = timemap.split("\n");
                            for (const line of lines) {
                                if (line.contains("memento")) {
                                    const link = line.slice(1, line.indexOf(">"));
                                    const first = link.substring(0, 41);
                                    const second = link.substring(42);
                                    items.push(await getFeedItems({
                                        name: feed.name,
                                        url: first + "id_" + second,
                                        folder: feed.folder
                                    }));
                                }
                            }

                            modal.setMessage(t("scanning_duplicates"));

                            for (const feed of plugin.settings.items) {
                                for (const content of items) {
                                    if (feed.folder === content.folder && feed.name === content.name) {
                                        const sortedItems = content.items.sort((a, b) => {
                                            return moment(b.pubDate).diff(moment(a.pubDate));
                                        });
                                        for (const item of sortedItems) {
                                            const filter = feed.items.filter((filterItem) => {
                                                return filterItem.folder === item.folder && filterItem.title === item.title;
                                            });
                                            if (filter.length === 0) {
                                                feed.items.push(item);
                                            }
                                        }
                                    }
                                }
                            }

                            await plugin.writeFeedContent(() => {
                                return plugin.settings.items;
                            });
                            displayFeedList(plugin, container, false);
                            modal.setMessage(t("refreshed_feeds"));
                            modal.close();
                        });
                })
                .addExtraButton((b) => {
                    b
                        .setDisabled(disabled)
                        .setIcon("lucide-trash")
                        .setTooltip(t("delete"))
                        .onClick(async () => {
                            const feeds = plugin.settings.feeds;
                            feeds.remove(feed);
                            await plugin.writeFeeds(() => feeds);

                            //delete wallabag.xml items from feed
                            let content = plugin.settings.items;
                            content = content.filter((content) => {
                                return content.name !== feed.name;
                            });
                            await plugin.writeFeedContent(() => content);

                            displayFeedList(plugin, container);
                        });
                });
        }
    }
}