`):"{{ INVALID TEMPLATE TAG - operator LIST is only applicable on an array }}":o==="ENUM"?Array.isArray(s)?s.join(", "):"{{ INVALID TEMPLATE TAG - operator ENUM is only applicable on an array }}":o==="FIRST"?Array.isArray(s)?s[0]:"{{ INVALID TEMPLATE TAG - operator FIRST is only applicable on an array }}":o==="LAST"?Array.isArray(s)?s[s.length-1]:"{{ INVALID TEMPLATE TAG - operator LAST is only applicable on an array }}":`{{INVALIDTEMPLATETAG-unknownoperator${o}}}`}return"{{ INVALID TEMPLATE TAG }}"}function rn(r,e){let t=e;for(let i of r)t!==void 0&&(t=t[i]);return t}function an(r){let e=r.length;if(e===0)return"";let t=r[0].length;if(t===0)return"";for(let o of r)if(o.length!==t)return"";let i=[];for(let o=0;o<t;o++){let a=0;for(let s of r)s[o].length>a&&(a=s[o].length);i.push(a)}let n="";for(let o=0;o<e;o++){n+="|";for(let a=0;a<t;a++){let s=r[o][a];s+=" ".repeat(i[a]-s.length),n+=" "+s+" |"}if(n+=`
</p>`,new Wn({target:this.containerEl,props:{models:this.plugin.settings.propertyMappingModels.map(i=>i.copy()),save:i=>{let n=[];for(let o of this.plugin.settings.propertyMappingModels)o.type===i.type?n.push(i):n.push(o);this.plugin.settings.propertyMappingModels=n,new C.Notice(`MDB: Property Mappings for ${i.type} saved successfully.`),this.plugin.saveSettings()}}})}}};var Di=class{constructor(){this.apis=[]}async query(e,t){console.debug(`MDB | api manager queried with "${e}"`);let i=this.apis.filter(n=>t.contains(n.apiName)).map(async n=>{try{return await n.searchByTitle(e)}catch(o){console.warn(o)}});return(await Promise.all(i)).flat()}async queryDetailedInfo(e){return await this.queryDetailedInfoById(e.id,e.dataSource)}async queryDetailedInfoById(e,t){for(let i of this.apis)if(i.apiName===t)return i.getById(e)}getApiByName(e){for(let t of this.apis)if(t.apiName===e)return t;return null}registerAPI(e){this.apis.push(e)}};var q=class{hasType(e){return this.types.contains(e)}hasTypeOverlap(e){return e.some(t=>this.hasType(t))}};var Ei=class extends q{constructor(t){super();this.apiDateFormat="DD MMM YYYY";this.plugin=t,this.apiName="OMDbAPI",this.apiDescription="A free API for Movies, Series and Games.",this.apiUrl="https://www.omdbapi.com/",this.types=["movie","series","game"],this.typeMappings=new Map,this.typeMappings.set("movie","movie"),this.typeMappings.set("series","series"),this.typeMappings.set("game","game")}async searchByTitle(t){if(console.log(`MDB | api "${this.apiName}" queried by Title`),!this.plugin.settings.OMDbKey)throw Error(`MDB | API key for ${this.apiName} missing.`);let i=`https://www.omdbapi.com/?s=${encodeURIComponent(t)}&apikey=${this.plugin.settings.OMDbKey}`,n=await fetch(i);if(n.status===401)throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);if(n.status!==200)throw Error(`MDB | Received status code ${n.status} from ${this.apiName}.`);let o=await n.json();if(o.Response==="False"){if(o.Error==="Movienotfound!")return[];throwError(`MDB | Received error from ${this.apiName}:
${JSON.stringify(o,void0,4)}`)}if(!o.Search)return[];let a=[];for(let s of o.Search){let l=this.typeMappings.get(s.Type.toLowerCase());l!==void 0&&(l==="movie"?a.push(new me({type:l,title:s.Title,englishTitle:s.Title,year:s.Year,dataSource:this.apiName,id:s.imdbID})):l==="series"?a.push(new Ce({type:l,title:s.Title,englishTitle:s.Title,year:s.Year,dataSource:this.apiName,id:s.imdbID})):l==="game"&&a.push(new pe({type:l,title:s.Title,englishTitle:s.Title,year:s.Year,dataSource:this.apiName,id:s.imdbID})))}return a}async getById(t){var s,l,p,d,c,f,u,M,g,m,_,b,D,h,y,w,S,T,E,x,v,F,P,A,Q,U,ee,_e,le;if(console.log(`MDB|api"${this.apiName}"queriedbyID`),!this.plugin.settings.OMDbKey)throw Error(`MDB|APIkeyfor${this.apiName}missing.`);let i=`https://www.omdbapi.com/?i=${encodeURIComponent(t)}&apikey=${this.plugin.settings.OMDbKey}`,n=await fetch(i);if(n.status===401)throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);if(n.status!==200)throw Error(`MDB | Received status code ${n.status} from ${this.apiName}.`);let o=await n.json();if(o.Response==="False")throw Error(`MDB | Received error from ${this.apiName}: ${o.Error}`);let a=this.typeMappings.get(o.Type.toLowerCase());if(a===void 0)throw Error(`${o.type.toLowerCase()} is an unsupported type.`);if(a==="movie")return new me({type:a,title:o.Title,englishTitle:o.Title,year:o.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${o.imdbID}/`,id:o.imdbID,plot:(s=o.Plot)!=null?s:"",genres:(p=(l=o.Genre)==null?void 0:l.split(", "))!=null?p:[],director:(c=(d=o.Director)==null?void 0:d.split(", "))!=null?c:[],writer:(u=(f=o.Writer)==null?void 0:f.split(", "))!=null?u:[],studio:["N/A"],duration:(M=o.Runtime)!=null?M:"unknown",onlineRating:Number.parseFloat((g=o.imdbRating)!=null?g:0),actors:(_=(m=o.Actors)==null?void 0:m.split(", "))!=null?_:[],image:(b=o.Poster)!=null?b:"",released:!0,streamingServices:[],premiere:(D=this.plugin.dateFormatter.format(o.Released,this.apiDateFormat))!=null?D:"unknown",userData:{watched:!1,lastWatched:"",personalRating:0}});if(a==="series")return new Ce({type:a,title:o.Title,englishTitle:o.Title,year:o.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${o.imdbID}/`,id:o.imdbID,plot:(h=o.Plot)!=null?h:"",genres:(w=(y=o.Genre)==null?void 0:y.split(", "))!=null?w:[],writer:(T=(S=o.Writer)==null?void 0:S.split(", "))!=null?T:[],studio:[],episodes:0,duration:(E=o.Runtime)!=null?E:"unknown",onlineRating:Number.parseFloat((x=o.imdbRating)!=null?x:0),actors:(F=(v=o.Actors)==null?void 0:v.split(", "))!=null?F:[],image:(P=o.Poster)!=null?P:"",released:!0,streamingServices:[],airing:!1,airedFrom:(A=this.plugin.dateFormatter.format(o.Released,this.apiDateFormat))!=null?A:"unknown",airedTo:"unknown",userData:{watched:!1,lastWatched:"",personalRating:0}});if(a==="game")return new pe({type:a,title:o.Title,englishTitle:o.Title,year:o.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${o.imdbID}/`,id:o.imdbID,developers:[],publishers:[],genres:(U=(Q=o.Genre)==null?void 0:Q.split(", "))!=null?U:[],onlineRating:Number.parseFloat((ee=o.imdbRating)!=null?ee:0),image:(_e=o.Poster)!=null?_e:"",released:!0,releaseDate:(le=this.plugin.dateFormatter.format(o.Released,this.apiDateFormat))!=null?le:"unknown",userData:{played:!1,personalRating:0}})}};var Ci=class extends q{constructor(t){super();this.apiDateFormat="YYYY-MM-DDTHH:mm:ssZ";this.plugin=t,this.apiName="MALAPI",this.apiDescription="A free API for Anime. Some results may take a long time to load.",this.apiUrl="https://jikan.moe/",this.types=["movie","series"],this.typeMappings=new Map,this.typeMappings.set("movie","movie"),this.typeMappings.set("special","special"),this.typeMappings.set("tv","series"),this.typeMappings.set("ova","ova")}async searchByTitle(t){var s,l,p,d,c,f,u,M,g,m,_,b,D,h,y,w,S,T,E;console.log(`MDB | api "${this.apiName}" queried by Title`);let i=`https://api.jikan.moe/v4/anime?q=${encodeURIComponent(t)}&limit=20${this.plugin.settings.sfwFilter?"&sfw":""}`,n=await fetch(i);if(n.status!==200)throw Error(`MDB | Received status code ${n.
`}),t.createEl("small",{text:`${e.type.toUpperCase()+(e.subType?` (${e.subType})`:"")}from${e.dataSource}`})}submit(){this.busy||(this.busy=!0,this.submitButton.setButtonText("Creating entry..."),this.submitCallback({selected:this.selectModalElements.filter(e=>e.isActive()).map(e=>e.value)}))}skip(){this.skipButton.setButtonText("Skipping..."),this.skipCallback()}onClose(){this.closeCallback()}};var Te=require("obsidian");var He=require("obsidian");var Hi=class extends He.Modal{constructor(e,t){t=Object.assign({},Vn,t),super(e.app),this.plugin=e,this.title=t.modalTitle,this.elements=t.elements,this.markdownComponent=new He.Component}setSubmitCallback(e){this.submitCallback=e}setCloseCallback(e){this.closeCallback=e}async preview(){let{contentEl:e}=this;e.addClass("media-db-plugin-preview-modal"),e.createEl("h2",{text:this.title});let t=e.createDiv({cls:"media-db-plugin-preview-wrapper"});this.markdownComponent.load();for(let n of this.elements){t.createEl("h3",{text:n.englishTitle});let o=t.createDiv({cls:"media-db-plugin-preview"}),a=this.plugin.generateMediaDbNoteFrontmatterPreview(n);a=`\`\`\`yaml
${a}\`\`\``;try{awaitHe.MarkdownRenderer.render(this.app,a,o,"",this.markdownComponent)}catch(s){console.warn("mdb | error during rendering of preview",s)}}e.createDiv({cls:"media-db-plugin-spacer"});leti=newHe.Setting(e);i.addButton(n=>{n.setButtonText("Cancel"),n.onClick(()=>this.close()),n.buttonEl.addClass("media-db-plugin-button"),this.cancelButton=n}),i.addButton(n=>{n.setButtonText("Ok"),n.setCta(),n.onClick(()=>this.submitCallback({confirmed:!0})),n.buttonEl.addClass("media-db-plugin-button"),this.submitButton=n})}onOpen(){this.preview()}onClose(){this.markdownComponent.unload(),this.closeCallback()}};varxe=require("obsidian");varVi=classextendsxe.Modal{constructor(e,t){t=Object.assign({},Gn,t),super(e.app),this.plugin=e,this.selectedTypes=[],this.title=t.modalTitle,this.query=t.prefilledSearchString;for(letiofPe)this.selectedTypes.push({name:i,selected:t.preselectedTypes.contains(i)})}setSubmitCallback(e){this.submitCallback=e}setCloseCallback(e){this.closeCallback=e}keyPressCallback(e){e.key==="Enter"&&this.search()}asyncsearch(){if(!this.query||this.query.length<3){newxe.Notice("MDB | Query too short");return}lete=this.selectedTypes.filter(t=>t.selected).map(t=>t.name);if(e.length===0){newxe.Notice("MDB | No Type selected");return}this.isBusy||(this.isBusy=!0,this.searchBtn.setDisabled(!1),this.searchBtn.setButtonText("Searching..."),this.submitCallback({query:this.query,types:e}))}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:this.title});lett="Search by title",i=newxe.TextComponent(e),n=null;i.inputEl.style.width="100%",i.setPlaceholder(t),i.setValue(this.query),i.onChange(o=>this.query=o),i.inputEl.addEventListener("keydown",this.keyPressCallback.bind(this)),e.appendChild(i.inputEl),i.inputEl.focus(),e.createDiv({cls:"media-db-plugin-spacer"}),e.createEl("h3",{text:"APIs to search"});for(letoofPe){leta=e.createEl("div",{cls:"media-db-plugin-list-wrapper"});a.createEl("div",{cls:"media-db-plugin-list-text-wrapper"}).createEl("span",{text:zt(o),cls:"media-db-plugin-list-text"});letl=a.createEl("div",{cls:"media-db-plugin-list-toggle"}),p=newxe.ToggleComponent(l);p.setTooltip(zt(o)),p.setValue(this.selectedTypes.find(d=>d.name===o).selected),p.getValue()&&(n=p),p.onChange(d=>{d?(n&&n!==p&&(n.setValue(!1),this.selectedTypes.find(c=>c.name===o).selected=!1),n=p,this.selectedTypes.find(c=>c.name===o).selected=!0):(n=null,this.selectedTypes.find(c=>c.name===o).selected=!1)}),l.appendChild(p.toggleEl)}e.createDiv({cls:"media-db-plugin-spacer"}),newxe.Setting(e).addButton(o=>{o.setButtonText("Cancel"),o.onClick(()=>this.close()),o.buttonEl.addClass("media-db-plugin-button")}).addButton(o=>{o.setButtonText("Ok"),o.setCta(),o.onClick(()=>{this.search()}),o.buttonEl.addClass("media-db-plugin-button"),this.searchBtn=o})}onClose(){this.closeCallback();let{contentEl:e}=this;e.empty()}};varGn={modalTitle:"Media DB Search",preselectedTypes:[],prefilledSearchString:""},qn={modalTitle:"Media DB Advanced Search",preselectedAPIs:[],prefilledSearchString:""},Un={modalTitle:"Media DB Id Search",preselectedAPI:"",prefilledSearchString:""},Hn={modalTitle:"Media DB Search Results",elements:[],multiSelect:!0,skipButton:!1},Vn={modalTitle:"Media DB Preview",elements:[]},Gi=class{constructor(e){this.plugin=e}asynccreateSearchModal(e){lett=newVi(this.plugin,e);return{searchModalResult:awaitnewPromise(n=>{t.setSubmitCallback(o=>n({code:"SUCCESS",data:o})),t.setCloseCallback(o=>{o&&n({code:"ERROR",error:o}),n({code:"CLOSE"})}),t.open()}),searchModal:t}}asyncopenSearchModal(e,t){let{searchModalResult:i,searchModal:n}=awaitthis.createSearchModal(e);if(console.debug(`MDB | searchModal closed with code ${i.code}`),i.code==="ERROR"){console.warn(i.error),newTe.Notice(i.error.toString()),n.close();return}if(i.code!=="CLOSE")try{leto=awaitt(i.data);returnn.close(),o}catch(o){console.warn(o),newTe.Notice(o.toString()),n.close();return}}asynccreateAdvancedSearchModal(e){lett=newIi(this.plugin,e);return{advancedSearchModalResult:awaitnewPromise(n=>{t.setSubmitCallback(o=>n({code:"SUCCESS",data:o})),t
`)?a.substring(1):a,i+=a,{fileMetadata:t,fileContent:i}}async attachTemplate(t,i,n){if(!n)return{fileMetadata:t,fileContent:i};let o=this.getMetaDataFromFileContent(n);t=Object.assign(o,t);let a=new RegExp(this.frontMatterRexExpPattern),s=n.replace(a,"");return i+=s,{fileMetadata:t,fileContent:i}}getMetaDataFromFileContent(t){let i,o=new RegExp(this.frontMatterRexExpPattern).exec(t);if(!o)return{};let a=o[0];return a?(a=a.substring(4),a=a.substring(0,a.length-3),i=(0,z.parseYaml)(a),i||(i={}),console.debug("MDB | metadata read from file content",i),i):{}}getMetadataFromFileCache(t){let i=this.app.metadataCache.getFileCache(t).frontmatter;return structuredClone(i!=null?i:{})}async createNote(t,i,n){var p;let o=(p=n.folder)!=null?p:this.app.vault.getAbstractFileByPath("/");t=on(t);let a=`${o.path}/${t}.md`,s=this.app.vault.getAbstractFileByPath(a);s&&await this.app.vault.delete(s);let l=await this.app.vault.create(a,i);if(console.debug(`MDB|creatednewfileat${a}`),n.openNote){let d=this.app.workspace.getUnpinnedLeaf();if(!d){console.warn("MDB | no active leaf, not opening newly created note");return}await d.openFile(l,{state:{mode:"source"}})}return l}async updateActiveNote(t=!1){let i=this.app.workspace.getActiveFile();if(!i)throw new Error("MDB | there is no active note");let n=this.getMetadataFromFileCache(i);if(n=this.modelPropertyMapper.convertObjectBack(n),console.debug("MDB | read metadata",n),!(n!=null&&n.type)||!(n!=null&&n.dataSource)||!(n!=null&&n.id))throw new Error("MDB | active note is not a Media DB entry or is missing metadata");let o=n,a=this.mediaTypeManager.createMediaTypeModelFromMediaType(o,o.type),s=await this.apiManager.queryDetailedInfoById(o.id,o.dataSource);s&&(s=Object.assign(a,s.getWithOutUserData()),t?await this.createMediaDbNoteFromModel(s,{attachFile:i,folder:i.parent,openNote:!0}):await this.createMediaDbNoteFromModel(s,{attachTemplate:!0,folder:i.parent,openNote:!0}))}async createEntriesFromFolder(t){let i=[],n=!1,{selectedAPI:o,titleFieldName:a,appendContent:s}=await new Promise(l=>{new Bi(this.app,this,(p,d,c)=>{l({selectedAPI:p,titleFieldName:d,appendContent:c})}).open()});for(let l of t.children)if(l instanceof z.TFile){let p=l;if(n){i.push({filePath:p.path,error:"user canceled"});continue}let c=this.getMetadataFromFileCache(p)[a];if(!c){i.push({filePath:p.path,error:`metadatafield'${a}'notfoundorempty`});continue}let f=[];try{f=await this.apiManager.query(c,[o])}catch(m){i.push({filePath:p.path,error:m.toString()});continue}if(!f||f.length===0){i.push({filePath:p.path,error:"no search results"});continue}let{selectModalResult:u,selectModal:M}=await this.modalHelper.createSelectModal({elements:f,skipButton:!0,modalTitle:`Resultsfor'${c}'`});if(u.code==="ERROR"){i.push({filePath:p.path,error:u.error.message}),M.close();continue}if(u.code==="CLOSE"){i.push({filePath:p.path,error:"user canceled"}),M.close(),n=!0;continue}if(u.code==="SKIP"){i.push({filePath:p.path,error:"user skipped"}),M.close();continue}if(u.data.selected.length===0){i.push({filePath:p.path,error:"no search results selected"});continue}let g=await this.queryDetails(u.data.selected);await this.createMediaDbNotes(g,s?p:null),M.close()}i.length>0&&await this.createErroredFilesReport(i)}async createErroredFilesReport(t){let i=`MDB-bulkimporterrorreport${ln(newDate)}`,n=`${i}.md`,o=[["file","error"]].concat(t.map(s=>[s.filePath,s.error])),a=`#${i}
${an(o)}`;await this.app.vault.create(n,a)}async loadSettings(){let t=await this.loadData(),i=jn(this),n=Object.assign({},i,t),o=[];for(let a of i.propertyMappingModels){let s=n.propertyMappingModels.find(l=>l.type===a.type);if(s===void 0)o.push(a);else{let l=[];for(let p of a.properties){let d=s.properties.find(c=>c.property===p.property);d===void 0?l.push(p):l.push(new dt(d.property,d.newProperty,d.mapping,p.locked))}o.push(new Ft(s.type,l))}}n.propertyMappingModels=o,this.settings=n}async saveSettings(){this.mediaTypeManager.updateTemplates(this.settings),this.mediaTypeManager.updateFolders(this.settings),this.dateFormatter.setFormat(this.settings.customDateFormat),await this.saveData(this.settings)}};