diff --git a/src/api/opld.ts b/src/api/opld.ts index 4b7f3a7..910a6d5 100644 --- a/src/api/opld.ts +++ b/src/api/opld.ts @@ -1,79 +1,12 @@ -import axios, { Axios, AxiosInstance } from "axios"; -import * as cheerio from 'cheerio'; -import { Notice } from "obsidian"; +const OldpApi = require('oldp-api'); -export interface OldpSearchResponseItem { - link: string; - title: string; - snippet: string; -} +var defaultClient = OldpApi.ApiClient.instance; + +var api_key = defaultClient.authentications['api_key']; +api_key.apiKey = "YOUR API KEY"; + +var LawBooksApi = new OldpApi.LawBooksApi(); -export class OldpApi { - private readonly corsProxyUrl = 'https://cors-anywhere.herokuapp.com'; - private readonly baseUrl = 'https://de.openlegaldata.io'; - private axiosClient: AxiosInstance; - private abortController: AbortController | null = null; - constructor() { - this.axiosClient = axios.create({ - maxRedirects: 0, - responseType: 'text', - }); - } - private async getRawSearchResults(searchTerm: string): Promise { - /*if (this.abortController) { - // Abort the current request - this.abortController.abort(); - } - - // TODO: fix this, after one abort all requests afterwords don't get used - this.abortController = new AbortController();*/ - - try { - const url = `${this.baseUrl}/search/?selected_facets=facet_model_name_exact%3ALaw&q=${encodeURIComponent(searchTerm)}`; - - const response = await this.axiosClient.get(`${this.corsProxyUrl}/${url}`, { - //signal: this.abortController.signal, - }); - const html = response.data; - - return html; - } catch (error: any) { - // handle aborted "error" - //if (this.abortController.signal.aborted || error?.code === 'ERR_CANCELED') return null; - - console.error('Error fetching search results:', error); - - new Notice(`An error occurred while trying to request the oldp.io API. Please check your internet connection. Code: ${error?.code}`); - return null; - } - } - - private parseSearchResults(data: string): OldpSearchResponseItem[] { - const webDocument = cheerio.load(data); - const searchItems: OldpSearchResponseItem[] = []; - - webDocument('.search-items li').each((index, element) => { - const link = `${this.baseUrl}${webDocument(element).find('a').attr('href')}`; - const title = (webDocument(element).find('h4').text()).replace('(Law)', '').trim(); - const snippet = webDocument(element).find('.search-snippet').text().trim(); - - searchItems.push({ - link, - title, - snippet - }); - }); - - return searchItems; - } - - public async search(searchTerm: string): Promise { - const rawSearchResult = await this.getRawSearchResults(searchTerm); - if (rawSearchResult === null) return []; - - return this.parseSearchResults(rawSearchResult); - } -} \ No newline at end of file diff --git a/src/api/redundant-opld.ts b/src/api/redundant-opld.ts new file mode 100644 index 0000000..4b7f3a7 --- /dev/null +++ b/src/api/redundant-opld.ts @@ -0,0 +1,79 @@ +import axios, { Axios, AxiosInstance } from "axios"; +import * as cheerio from 'cheerio'; +import { Notice } from "obsidian"; + +export interface OldpSearchResponseItem { + link: string; + title: string; + snippet: string; +} + + +export class OldpApi { + private readonly corsProxyUrl = 'https://cors-anywhere.herokuapp.com'; + private readonly baseUrl = 'https://de.openlegaldata.io'; + private axiosClient: AxiosInstance; + private abortController: AbortController | null = null; + + constructor() { + this.axiosClient = axios.create({ + maxRedirects: 0, + responseType: 'text', + }); + } + + private async getRawSearchResults(searchTerm: string): Promise { + /*if (this.abortController) { + // Abort the current request + this.abortController.abort(); + } + + // TODO: fix this, after one abort all requests afterwords don't get used + this.abortController = new AbortController();*/ + + try { + const url = `${this.baseUrl}/search/?selected_facets=facet_model_name_exact%3ALaw&q=${encodeURIComponent(searchTerm)}`; + + const response = await this.axiosClient.get(`${this.corsProxyUrl}/${url}`, { + //signal: this.abortController.signal, + }); + const html = response.data; + + return html; + } catch (error: any) { + // handle aborted "error" + //if (this.abortController.signal.aborted || error?.code === 'ERR_CANCELED') return null; + + console.error('Error fetching search results:', error); + + new Notice(`An error occurred while trying to request the oldp.io API. Please check your internet connection. Code: ${error?.code}`); + return null; + } + } + + private parseSearchResults(data: string): OldpSearchResponseItem[] { + const webDocument = cheerio.load(data); + const searchItems: OldpSearchResponseItem[] = []; + + webDocument('.search-items li').each((index, element) => { + const link = `${this.baseUrl}${webDocument(element).find('a').attr('href')}`; + const title = (webDocument(element).find('h4').text()).replace('(Law)', '').trim(); + const snippet = webDocument(element).find('.search-snippet').text().trim(); + + searchItems.push({ + link, + title, + snippet + }); + }); + + return searchItems; + } + + public async search(searchTerm: string): Promise { + const rawSearchResult = await this.getRawSearchResults(searchTerm); + if (rawSearchResult === null) return []; + + return this.parseSearchResults(rawSearchResult); + } +} \ No newline at end of file diff --git a/src/law-sidebar.ts b/src/law-sidebar.ts index bf6c74e..f0b46ee 100644 --- a/src/law-sidebar.ts +++ b/src/law-sidebar.ts @@ -15,11 +15,24 @@ export class LawRefView extends ItemView { return "Example view"; } + parseLawRefList(LawRefList: string[]) { + const suggestionContainer = this.containerEl.children[1].getElementsByClassName("lawRef-suggestion-container")[0]; + suggestionContainer.empty(); + LawRefList.forEach((lawRef) => { + const lawRefElement = suggestionContainer.createDiv({ cls: "lawRef-suggestion" }); + + lawRefElement.createDiv({ cls: "lawRef-suggestion-element"}).createEl("h2", { text: lawRef }); + }); + + + }; + async onOpen() { console.log("Example view opened"); const container = this.containerEl.children[1]; container.empty(); - container.createEl("h2", { text: "Gesetzesauszüge" }); + container.createEl("h1", { text: "Gesetzesauszüge" }); + container.createDiv({ cls: "lawRef-suggestion-container" }); } async onClose() { diff --git a/src/lawSuggester.ts b/src/lawSuggester.ts index be17ac5..ff49525 100644 --- a/src/lawSuggester.ts +++ b/src/lawSuggester.ts @@ -1,3 +1,5 @@ +/** + import LawRefPlugin from "./main"; import { Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo, TFile } from "obsidian"; import { OldpApi, OldpSearchResponseItem } from "./api/opld"; @@ -86,3 +88,4 @@ export default class LawSuggester extends EditorSuggest this.context.editor.replaceRange(linkEl, start, end); } } + */ \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 5f3ff1c..9cf81a1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,7 +1,7 @@ import { App, Modal, Notice, Plugin, PluginSettingTab, Setting, Vault, Workspace, WorkspaceLeaf, MarkdownPostProcessorContext, parseFrontMatterEntry, View, MarkdownView } from 'obsidian'; import { LawRefView, VIEW_TYPE_LAWREF } from './law-sidebar'; -import { OldpApi } from './api/opld'; -import LawSuggester from './lawSuggester'; +//import { OldpApi } from './api/opld'; +//import LawSuggester from './lawSuggester'; import { lawRefPluginEditorProcessor, } from './law-editor-processor'; // Remember to rename these classes and interfaces! @@ -16,7 +16,7 @@ const DEFAULT_SETTINGS: LawRefPluginSettings = { export default class LawRefPlugin extends Plugin { settings: LawRefPluginSettings; - private readonly OldpApi = new OldpApi(); + //private readonly OldpApi = new OldpApi(); async onload() { await this.loadSettings(); this.registerView(VIEW_TYPE_LAWREF, (leaf) => new LawRefView(leaf)) @@ -25,7 +25,17 @@ export default class LawRefPlugin extends Plugin { this.addSettingTab(new LawRefPluginSettingTab(this.app, this)); this.app.workspace.onLayoutReady(() => {this.activateView()}); + this.app.workspace.on('file-open', (file) => { + const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_LAWREF); + if (leaves.length > 0) { + const view = leaves[0].view as LawRefView; + const LawRefList = this.getFrontMatterMeta(); + if (LawRefList) { + view.parseLawRefList(LawRefList); + } + } + }); /** If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin) Using this function will automatically remove the event listener when this plugin is disabled. this.registerDomEvent(document, 'click', (evt: MouseEvent) => { @@ -43,7 +53,7 @@ export default class LawRefPlugin extends Plugin { // register suggestor on § key if (this.settings.useSuggester===true){ - this.registerEditorSuggest(new LawSuggester(this)) + //this.registerEditorSuggest(new LawSuggester(this)) } } @@ -76,7 +86,7 @@ export default class LawRefPlugin extends Plugin { // "Reveal" the leaf in case it is in a collapsed sidebar workspace.revealLeaf(leaf); } - /**async getFrontMatterMeta(){ + getFrontMatterMeta(){ const { workspace } = this.app; const actFile = workspace.getActiveFile(); if (!actFile) return @@ -84,20 +94,14 @@ export default class LawRefPlugin extends Plugin { if (!actFilemetadata) return console.log("no metadata"); let actFileFrontmatter = actFilemetadata.frontmatter; let LawRefList = parseFrontMatterEntry(actFileFrontmatter, '§'); + console.log(typeof LawRefList); if (LawRefList) { console.log(LawRefList); + return LawRefList; + } else { + return []; } - this.app.workspace.getLeavesOfType(VIEW_TYPE_LAWREF).forEach((leaf) => { - if (leaf.view instanceof LawRefView) { - const container = leaf.view.containerEl.children[1]; - container.empty; - console.log(container) - LawRefList.forEach((element:string) => { - const elementResponse = this.OldpApi.search(element); - container.createEl("p", {cls: "LawRefContainer", text: element})}); - } - }); - }**/ + } async loadSettings() {