You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
113 KiB

3 years ago
/*
12 months ago
-------------------------------------------
Media DB Plugin - Release Build
-------------------------------------------
By: Moritz Jung (https://mprojectscode.github.io/)
Time: Tue, 12 Dec 2023 20:23:33 GMT
Version: 0.6.0
-------------------------------------------
3 years ago
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
12 months ago
var si=Object.defineProperty;var Vo=Object.getOwnPropertyDescriptor;var Yo=Object.getOwnPropertyNames;var Go=Object.prototype.hasOwnProperty;var zo=(o,t,e)=>t in o?si(o,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[t]=e;var Ko=(o,t)=>{for(var e in t)si(o,e,{get:t[e],enumerable:!0})},Xo=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Yo(t))!Go.call(o,i)&&i!==e&&si(o,i,{get:()=>t[i],enumerable:!(r=Vo(t,i))||r.enumerable});return o};var Zo=o=>Xo(si({},"__esModule",{value:!0}),o);var z=(o,t,e)=>(zo(o,typeof t!="symbol"?t+"":t,e),e);var la={};Ko(la,{default:()=>zi});module.exports=Zo(la);var ne=require("obsidian");var P=require("obsidian");var so=require("obsidian");var ao=require("obsidian");var B="top",H="bottom",q="right",L="left",li="auto",We=[B,H,q,L],Re="start",Ke="end",Rr="clippingParents",pi="viewport",vt="popper",Or="reference",Ki=We.reduce(function(o,t){return o.concat([t+"-"+Re,t+"-"+Ke])},[]),di=[].concat(We,[li]).reduce(function(o,t){return o.concat([t,t+"-"+Re,t+"-"+Ke])},[]),Jo="beforeRead",Qo="read",en="afterRead",tn="beforeMain",rn="main",on="afterMain",nn="beforeWrite",an="write",sn="afterWrite",Ar=[Jo,Qo,en,tn,rn,on,nn,an,sn];function K(o){return o?(o.nodeName||"").toLowerCase():null}function $(o){if(o==null)return window;if(o.toString()!=="[object Window]"){var t=o.ownerDocument;return t&&t.defaultView||window}return o}function pe(o){var t=$(o).Element;return o instanceof t||o instanceof Element}function V(o){var t=$(o).HTMLElement;return o instanceof t||o instanceof HTMLElement}function wt(o){if(typeof ShadowRoot=="undefined")return!1;var t=$(o).ShadowRoot;return o instanceof t||o instanceof ShadowRoot}function ln(o){var t=o.state;Object.keys(t.elements).forEach(function(e){var r=t.styles[e]||{},i=t.attributes[e]||{},n=t.elements[e];!V(n)||!K(n)||(Object.assign(n.style,r),Object.keys(i).forEach(function(a){var s=i[a];s===!1?n.removeAttribute(a):n.setAttribute(a,s===!0?"":s)}))})}function pn(o){var t=o.state,e={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,e.popper),t.styles=e,t.elements.arrow&&Object.assign(t.elements.arrow.style,e.arrow),function(){Object.keys(t.elements).forEach(function(r){var i=t.elements[r],n=t.attributes[r]||{},a=Object.keys(t.styles.hasOwnProperty(r)?t.styles[r]:e[r]),s=a.reduce(function(l,p){return l[p]="",l},{});!V(i)||!K(i)||(Object.assign(i.style,s),Object.keys(n).forEach(function(l){i.removeAttribute(l)}))})}}var Nr={name:"applyStyles",enabled:!0,phase:"write",fn:ln,effect:pn,requires:["computeStyles"]};function X(o){return o.split("-")[0]}var fe=Math.max,Xe=Math.min,Oe=Math.round;function xt(){var o=navigator.userAgentData;return o!=null&&o.brands&&Array.isArray(o.brands)?o.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function Wt(){return!/^((?!chrome|android).)*safari/i.test(xt())}function de(o,t,e){t===void 0&&(t=!1),e===void 0&&(e=!1);var r=o.getBoundingClientRect(),i=1,n=1;t&&V(o)&&(i=o.offsetWidth>0&&Oe(r.width)/o.offsetWidth||1,n=o.offsetHeight>0&&Oe(r.height)/o.offsetHeight||1);var a=pe(o)?$(o):window,s=a.visualViewport,l=!Wt()&&e,p=(r.left+(l&&s?s.offsetLeft:0))/i,d=(r.top+(l&&s?s.offsetTop:0))/n,c=r.width/i,u=r.height/n;return{width:c,height:u,top:d,right:p+c,bottom:d+u,left:p,x:p,y:d}}function Ze(o){var t=de(o),e=o.offsetWidth,r=o.offsetHeight;return Math.abs(t.width-e)<=1&&(e=t.width),Math.abs(t.height-r)<=1&&(r=t.height),{x:o.offsetLeft,y:o.offsetTop,width:e,height:r}}function qt(o,t){var e=t.getRootNode&&t.getRootNode();if(o.contains(t))return!0;if(e&&wt(e)){var r=t;do{if(r&&o.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function ae(o){return $(o).getComputedStyle(o)}function Xi(o){return["table","td","th"].indexOf(K(o))>=0}function ee(o){return((pe(o)?o.ownerDocument:o.document)||window.document).documentElement}function Ae(o){return K(o)==="html"?o:o.assignedSlot||o.parentNode||(wt(o)?o.host:null)||ee(o)}function Br(o){return!V(o)||ae(o).position==="fixed"?null:o.o
`):"{{ INVALID TEMPLATE TAG - operator LIST is only applicable on an array }}":i==="ENUM"?Array.isArray(a)?a.join(", "):"{{ INVALID TEMPLATE TAG - operator ENUM is only applicable on an array }}":`{{ INVALID TEMPLATE TAG - unknown operator ${i} }}`}return"{{ INVALID TEMPLATE TAG }}"}function eo(o,t){let e=t;for(let r of o)e!==void 0&&(e=e[r]);return e}function ro(o){let t=o.length;if(t===0)return"";let e=o[0].length;if(e===0)return"";for(let n of o)if(n.length!==e)return"";let r=[];for(let n=0;n<e;n++){let a=0;for(let s of o)s[n].length>a&&(a=s[n].length);r.push(a)}let i="";for(let n=0;n<t;n++){i+="|";for(let a=0;a<e;a++){let s=o[n][a];s+=" ".repeat(r[a]-s.length),i+=" "+s+" |"}if(i+=`
`,n===0){i+="|";for(let a=0;a<e;a++)i+=" "+"-".repeat(r[a])+" |";i+=`
`}}return i}var oo=o=>createFragment(t=>t.createDiv().innerHTML=o);function Rn(o){return`${o.getMonth()+1}-${o.getDate()}-${o.getFullYear()}`}function On(o){return`${o.getHours()}-${o.getMinutes()}-${o.getSeconds()}`}function no(o){return`${Rn(o)} ${On(o)}`}function fi(o,t){return(o%t+t)%t}function fr(o){return o.charAt(0).toUpperCase()+o.slice(1)}var rt=class extends Error{constructor(t){super(t)}},Gt=class extends Error{constructor(t){super(t)}};function R(o,t,e){for(let r in o)o[r]=t.hasOwnProperty(r)?t[r]:e[r]}function zt(o){return o.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b([A-Z]+)([A-Z])([a-z])/,"$1 $2$3").replace(/^./,function(t){return t.toUpperCase()})}var hr=class{constructor(t,e,r){this.owner=t,this.containerEl=e,e.on("click",".suggestion-item",this.onSuggestionClick.bind(this)),e.on("mousemove",".suggestion-item",this.onSuggestionMouseover.bind(this)),r.register([],"ArrowUp",i=>{if(!i.isComposing)return this.setSelectedItem(this.selectedItem-1,!0),!1}),r.register([],"ArrowDown",i=>{if(!i.isComposing)return this.setSelectedItem(this.selectedItem+1,!0),!1}),r.register([],"Enter",i=>{if(!i.isComposing)return this.useSelectedItem(i),!1})}onSuggestionClick(t,e){t.preventDefault();let r=this.suggestions.indexOf(e);this.setSelectedItem(r,!1),this.useSelectedItem(t)}onSuggestionMouseover(t,e){let r=this.suggestions.indexOf(e);this.setSelectedItem(r,!1)}setSuggestions(t){this.containerEl.empty();let e=[];t.forEach(r=>{let i=this.containerEl.createDiv("suggestion-item");this.owner.renderSuggestion(r,i),e.push(i)}),this.values=t,this.suggestions=e,this.setSelectedItem(0,!1)}useSelectedItem(t){let e=this.values[this.selectedItem];e&&this.owner.selectSuggestion(e,t)}setSelectedItem(t,e){let r=this.suggestions.length>0?to(t,this.suggestions.length):0,i=this.suggestions[this.selectedItem],n=this.suggestions[r];i==null||i.removeClass("is-selected"),n==null||n.addClass("is-selected"),this.selectedItem=r,e&&n.scrollIntoView(!1)}},St=class{constructor(t,e){this.app=t,this.inputEl=e,this.scope=new ao.Scope,this.suggestEl=createDiv("suggestion-container");let r=this.suggestEl.createDiv("suggestion");this.suggest=new hr(this,r,this.scope),this.scope.register([],"Escape",this.close.bind(this)),this.inputEl.addEventListener("input",this.onInputChanged.bind(this)),this.inputEl.addEventListener("focus",this.onInputChanged.bind(this)),this.inputEl.addEventListener("blur",this.close.bind(this)),this.suggestEl.on("mousedown",".suggestion-container",i=>{i.preventDefault()})}onInputChanged(){let t=this.inputEl.value,e=this.getSuggestions(t);e.length>0&&(this.suggest.setSuggestions(e),this.open(this.app.dom.appContainerEl,this.inputEl))}open(t,e){this.app.keymap.pushScope(this.scope),t.appendChild(this.suggestEl),this.popper=lr(e,this.suggestEl,{placement:"bottom-start",modifiers:[{name:"sameWidth",enabled:!0,fn:({state:r,instance:i})=>{let n=`${r.rects.reference.width}px`;r.styles.popper.width!==n&&(r.styles.popper.width=n,i.update())},phase:"beforeWrite",requires:["computeStyles"]}]})}close(){this.app.keymap.popScope(this.scope),this.suggest.setSuggestions([]),this.popper.destroy(),this.suggestEl.detach()}};var ye=class extends St{getSuggestions(t){let e=this.app.vault.getAllLoadedFiles(),r=[],i=t.toLowerCase();return e.forEach(n=>{n instanceof so.TFolder&&n.path.toLowerCase().contains(i)&&r.push(n)}),r}renderSuggestion(t,e){e.setText(t.path)}selectSuggestion(t){this.inputEl.value=t.path,this.inputEl.trigger("input"),this.close()}};var lo=require("obsidian"),Me=class extends St{getSuggestions(t){let e=this.app.vault.getAllLoadedFiles(),r=[],i=t.toLowerCase();return e.forEach(n=>{n instanceof lo.TFile&&n.name.toLowerCase().contains(i)&&r.push(n)}),r}renderSuggestion(t,e){e.setText(t.name)}selectSuggestion(t){this.inputEl.value=t.name,this.inputEl.trigger("input"),this.close()}};function re(){}function gr(o){return o()}function hi(){return Object.create(null)}function Ee(o){o.forEach(gr)}function gi(o){return typeof o=="function"}function Dt(o,t){return o!=o?t==t:o!==t||o&&typeof o=="object"||typeof o=="function"}function po(o){return
<p>Allow you to remap the metadata fields of newly created media db entries.</p>
<p>
The different options are:
<lu>
<li>"default": does no remapping and keeps the metadata field as it is</li>
<li>"remap": renames the metadata field to what ever you specify</li>
<li>"remove": removes the metadata field entirely</li>
</lu>
</p>
<p>
Don't forget to save your changes using the save button for each individual category.
12 months ago
</p>`,new Bo({target:this.containerEl,props:{models:this.plugin.settings.propertyMappingModels.map(i=>i.copy()),save:i=>{let n=[];for(let a of this.plugin.settings.propertyMappingModels)a.type===i.type?n.push(i):n.push(a);this.plugin.settings.propertyMappingModels=n,new P.Notice(`MDB: Property Mappings for ${i.type} saved successfully.`),this.plugin.saveSettings()}}})}};var Ei=class{constructor(){this.apis=[]}async query(t,e){console.debug(`MDB | api manager queried with "${t}"`);let r=[];for(let i of this.apis)if(e.contains(i.apiName)){let n=await i.searchByTitle(t);r=r.concat(n)}return r}async queryDetailedInfo(t){return await this.queryDetailedInfoById(t.id,t.dataSource)}async queryDetailedInfoById(t,e){for(let r of this.apis)if(r.apiName===e)return r.getById(t)}getApiByName(t){for(let e of this.apis)if(e.apiName===t)return e;return null}registerAPI(t){this.apis.push(t)}};var J=class{hasType(t){return this.types.contains(t)}hasTypeOverlap(t){for(let e of t)if(this.hasType(e))return!0;return!1}};var Ci=class extends J{constructor(e){super();this.apiDateFormat="DD MMM YYYY";this.plugin=e,this.apiName="OMDbAPI",this.apiDescription="A free API for Movies, Series and Games.",this.apiUrl="http://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(e){console.log(`MDB | api "${this.apiName}" queried by Title`);let r=`http://www.omdbapi.com/?s=${encodeURIComponent(e)}&apikey=${this.plugin.settings.OMDbKey}`,i=await fetch(r);if(i.status===401)throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);if(i.status!==200)throw Error(`MDB | Received status code ${i.status} from an API.`);let n=await i.json();if(n.Response==="False"){if(n.Error==="Movie not found!")return[];throw Error(`MDB | Received error from ${this.apiName}:
${JSON.stringify(n,void 0,4)}`)}if(!n.Search)return[];console.debug(n.Search);let a=[];for(let s of n.Search){let l=this.typeMappings.get(s.Type.toLowerCase());l!==void 0&&(l==="movie"?a.push(new ue({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(e){var s,l,p,d,c,u,m,M,g,f,T,w,D,h,y,b,_,x,E,v,C,S,F,k,te,N,I,Te,le;console.log(`MDB | api "${this.apiName}" queried by ID`);let r=`http://www.omdbapi.com/?i=${encodeURIComponent(e)}&apikey=${this.plugin.settings.OMDbKey}`,i=await fetch(r);if(i.status===401)throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);if(i.status!==200)throw Error(`MDB | Received status code ${i.status} from an API.`);let n=await i.json();if(n.Response==="False")throw Error(`MDB | Received error from ${this.apiName}: ${n.Error}`);let a=this.typeMappings.get(n.Type.toLowerCase());if(a===void 0)throw Error(`${n.type.toLowerCase()} is an unsupported type.`);if(a==="movie")return new ue({type:a,title:n.Title,englishTitle:n.Title,year:n.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${n.imdbID}/`,id:n.imdbID,plot:(s=n.Plot)!=null?s:"",genres:(p=(l=n.Genre)==null?void 0:l.split(", "))!=null?p:[],director:(c=(d=n.Director)==null?void 0:d.split(", "))!=null?c:[],writer:(m=(u=n.Writer)==null?void 0:u.split(", "))!=null?m:[],studio:["N/A"],duration:(M=n.Runtime)!=null?M:"unknown",onlineRating:Number.parseFloat((g=n.imdbRating)!=null?g:0),actors:(T=(f=n.Actors)==null?void 0:f.split(", "))!=null?T:[],image:(w=n.Poster)!=null?w:"",released:!0,streamingServices:[],premiere:(D=this.plugin.dateFormatter.format(n.Released,this.apiDateFormat))!=null?D:"unknown",userData:{watched:!1,lastWatched:"",personalRating:0}});if(a==="series")return new Ce({type:a,title:n.Title,englishTitle:n.Title,year:n.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${n.imdbID}/`,id:n.imdbID,plot:(h=n.Plot)!=null?h:"",genres:(b=(y=n.Genre)==null?void 0:y.split(", "))!=null?b:[],writer:(x=(_=n.Writer)==null?void 0:_.split(", "))!=null?x:[],studio:[],episodes:0,duration:(E=n.Runtime)!=null?E:"unknown",onlineRating:Number.parseFloat((v=n.imdbRating)!=null?v:0),actors:(S=(C=n.Actors)==null?void 0:C.split(", "))!=null?S:[],image:(F=n.Poster)!=null?F:"",released:!0,streamingServices:[],airing:!1,airedFrom:(k=this.plugin.dateFormatter.format(n.Released,this.apiDateFormat))!=null?k:"unknown",airedTo:"unknown",userData:{watched:!1,lastWatched:"",personalRating:0}});if(a==="game")return new Pe({type:a,title:n.Title,englishTitle:n.Title,year:n.Year,dataSource:this.apiName,url:`https://www.imdb.com/title/${n.imdbID}/`,id:n.imdbID,genres:(N=(te=n.Genre)==null?void 0:te.split(", "))!=null?N:[],onlineRating:Number.parseFloat((I=n.imdbRating)!=null?I:0),image:(Te=n.Poster)!=null?Te:"",released:!0,releaseDate:(le=this.plugin.dateFormatter.format(n.Released,this.apiDateFormat))!=null?le:"unknown",userData:{played:!1,personalRating:0}})}};var Pi=class extends J{constructor(e){super();this.apiDateFormat="YYYY-MM-DDTHH:mm:ssZ";this.plugin=e,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(e){var s,l,p,d,c,u,m,M,g,f,T,w,D,h,y,b,_,x,E;console.log(`MDB | api "${this.apiName}" queried by Title`);let r=`https://api.jikan.moe/v4/anime?q=${encodeURIComponent(e)}&limit=20${this.plugin.settings.sfwFilter?"&sfw":""}`,i=await fetch(r);if(console.debug(i),i.status!==200)throw Error(`MDB | Received status code ${i.status} from an API.`);let n=await i.json();console.debug(n);let a=[];for(let v of n.dat
`;return e}static toYamlString(t,e){if(t==null)return"null";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number")return t.toString();if(typeof t=="string")return'"'+t.replace('"','\\"')+'"';if(typeof t=="object"){let r="";if(Array.isArray(t))for(let i of t)r+=`
${o.calculateSpacing(e)} - ${o.toYamlString(i,e+1)}`;else for(let[i,n]of Object.entries(t))r+=`
${o.calculateSpacing(e)} ${i}: ${o.toYamlString(n,e+1)}`;return r}}static calculateSpacing(t){return" ".repeat(t*4)}};var ke=require("obsidian"),Bi=class extends ke.Modal{constructor(e,r,i){super(e);this.plugin=r,this.onSubmit=i,this.selectedApi=r.apiManager.apis[0].apiName}submit(){this.onSubmit(this.selectedApi,this.titleFieldName,this.appendContent),this.close()}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:"Import folder as Media DB entries"});let r=e.createEl("div",{cls:"media-db-plugin-list-wrapper"});r.createEl("div",{cls:"media-db-plugin-list-text-wrapper"}).createEl("span",{text:"API to search",cls:"media-db-plugin-list-text"});let n=new ke.DropdownComponent(r);n.onChange(u=>{this.selectedApi=u});for(let u of this.plugin.apiManager.apis)n.addOption(u.apiName,u.apiName);r.appendChild(n.selectEl),e.createDiv({cls:"media-db-plugin-spacer"}),e.createEl("h3",{text:"Append note content to Media DB entry."});let a=e.createEl("div",{cls:"media-db-plugin-list-wrapper"});a.createEl("div",{cls:"media-db-plugin-list-text-wrapper"}).createEl("span",{text:"If this is enabled, the plugin will override metadata fields with the same name.",cls:"media-db-plugin-list-text"});let l=a.createEl("div",{cls:"media-db-plugin-list-toggle"}),p=new ke.ToggleComponent(a);p.setValue(!1),p.onChange(u=>this.appendContent=u),l.appendChild(p.toggleEl),e.createDiv({cls:"media-db-plugin-spacer"}),e.createEl("h3",{text:"The name of the metadata field that should be used as the title to query."});let d="title",c=new ke.TextComponent(e);c.inputEl.style.width="100%",c.setPlaceholder(d),c.onChange(u=>this.titleFieldName=u),c.inputEl.addEventListener("keydown",u=>{u.key==="Enter"&&this.submit()}),e.appendChild(c.inputEl),e.createDiv({cls:"media-db-plugin-spacer"}),new ke.Setting(e).addButton(u=>{u.setButtonText("Cancel"),u.onClick(()=>this.close()),u.buttonEl.addClass("media-db-plugin-button")}).addButton(u=>{u.setButtonText("Ok"),u.setCta(),u.onClick(()=>{this.submit()}),u.buttonEl.addClass("media-db-plugin-button"),this.searchBtn=u})}onClose(){let{contentEl:e}=this;e.empty()}};var be=require("obsidian");var Ii=class extends be.Modal{constructor(e,r){r=Object.assign({},jo,r);super(e.app);this.plugin=e,this.selectedApis=[],this.title=r.modalTitle,this.query=r.prefilledSearchString;for(let i of this.plugin.apiManager.apis)this.selectedApis.push({name:i.apiName,selected:r.preselectedAPIs.contains(i.apiName)})}setSubmitCallback(e){this.submitCallback=e}setCloseCallback(e){this.closeCallback=e}keyPressCallback(e){e.key==="Enter"&&this.search()}async search(){if(!this.query||this.query.length<3){new be.Notice("MDB | Query too short");return}let e=this.selectedApis.filter(r=>r.selected).map(r=>r.name);if(e.length===0){new be.Notice("MDB | No API selected");return}this.isBusy||(this.isBusy=!0,this.searchBtn.setDisabled(!1),this.searchBtn.setButtonText("Searching..."),this.submitCallback({query:this.query,apis:e}))}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:this.title});let r="Search by title",i=new be.TextComponent(e);i.inputEl.style.width="100%",i.setPlaceholder(r),i.setValue(this.query),i.onChange(n=>this.query=n),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(let n of this.plugin.apiManager.apis){let a=e.createEl("div",{cls:"media-db-plugin-list-wrapper"}),s=a.createEl("div",{cls:"media-db-plugin-list-text-wrapper"});s.createEl("span",{text:n.apiName,cls:"media-db-plugin-list-text"}),s.createEl("small",{text:n.apiDescription,cls:"media-db-plugin-list-text"});let l=a.createEl("div",{cls:"media-db-plugin-list-toggle"}),p=new be.ToggleComponent(l);p.setTooltip(n.apiName),p.setValue(this.selectedApis.find(d=>d.name===n.apiName).selected),p.onChange(d=>{this.selectedApis.find(c=>c.name===n.apiName).selected=d}),l.appendChild(p.toggleEl)}e.createDiv({cls:"media-db-plugin-spacer"}),new be.Setting(e).addButton(n=>{n.setButtonText("Cancel"),n.onClick(()=>this.close()),n.buttonEl.addClass("med
`}),r.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 xe=require("obsidian");var Ve=require("obsidian");var Hi=class extends Ve.Modal{constructor(e,r){r=Object.assign({},Uo,r);super(e.app);this.plugin=e,this.title=r.modalTitle,this.elements=r.elements,this.markdownComponent=new Ve.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 r=e.createDiv({cls:"media-db-plugin-preview-wrapper"});this.markdownComponent.load();for(let n of this.elements){r.createEl("h3",{text:n.englishTitle});let a=r.createDiv({cls:"media-db-plugin-preview"}),s=this.plugin.generateMediaDbNoteFrontmatterPreview(n);s=`\`\`\`yaml
${s}\`\`\``;try{await Ve.MarkdownRenderer.render(this.app,s,a,"",this.markdownComponent)}catch(l){console.warn("mdb | error during rendering of preview",l)}}e.createDiv({cls:"media-db-plugin-spacer"});let i=new Ve.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()}};var we=require("obsidian");var Vi=class extends we.Modal{constructor(e,r){r=Object.assign({},Ho,r);super(e.app);this.plugin=e,this.selectedTypes=[],this.title=r.modalTitle,this.query=r.prefilledSearchString;for(let i of Fe)this.selectedTypes.push({name:i,selected:r.preselectedTypes.contains(i)})}setSubmitCallback(e){this.submitCallback=e}setCloseCallback(e){this.closeCallback=e}keyPressCallback(e){e.key==="Enter"&&this.search()}async search(){if(!this.query||this.query.length<3){new we.Notice("MDB | Query too short");return}let e=this.selectedTypes.filter(r=>r.selected).map(r=>r.name);if(e.length===0){new we.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});let r="Search by title",i=new we.TextComponent(e);i.inputEl.style.width="100%",i.setPlaceholder(r),i.setValue(this.query),i.onChange(n=>this.query=n),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(let n of Fe){let a=e.createEl("div",{cls:"media-db-plugin-list-wrapper"});a.createEl("div",{cls:"media-db-plugin-list-text-wrapper"}).createEl("span",{text:zt(n),cls:"media-db-plugin-list-text"});let l=a.createEl("div",{cls:"media-db-plugin-list-toggle"}),p=new we.ToggleComponent(l);p.setTooltip(zt(n)),p.setValue(this.selectedTypes.find(d=>d.name===n).selected),p.onChange(d=>{this.selectedTypes.find(c=>c.name===n).selected=d}),l.appendChild(p.toggleEl)}e.createDiv({cls:"media-db-plugin-spacer"}),new we.Setting(e).addButton(n=>{n.setButtonText("Cancel"),n.onClick(()=>this.close()),n.buttonEl.addClass("media-db-plugin-button")}).addButton(n=>{n.setButtonText("Ok"),n.setCta(),n.onClick(()=>{this.search()}),n.buttonEl.addClass("media-db-plugin-button"),this.searchBtn=n})}onClose(){this.closeCallback();let{contentEl:e}=this;e.empty()}};var Ho={modalTitle:"Media DB Search",preselectedTypes:[],prefilledSearchString:""},jo={modalTitle:"Media DB Advanced Search",preselectedAPIs:[],prefilledSearchString:""},Wo={modalTitle:"Media DB Id Search",preselectedAPI:"",prefilledSearchString:""},qo={modalTitle:"Media DB Search Results",elements:[],multiSelect:!0,skipButton:!1},Uo={modalTitle:"Media DB Preview",elements:[]},Yi=class{constructor(t){this.plugin=t}async createSearchModal(t){let e=new Vi(this.plugin,t);return{searchModalResult:await new Promise(i=>{e.setSubmitCallback(n=>i({code:0,data:n})),e.setCloseCallback(n=>{n&&i({code:3,error:n}),i({code:2})}),e.open()}),searchModal:e}}async openSearchModal(t,e){let{searchModalResult:r,searchModal:i}=await this.createSearchModal(t);if(console.debug(`MDB | searchModal closed with code ${r.code}`),r.code===3){console.warn(r.error),new xe.Notice(r.error.toString()),i.close();return}if(r.code!==2)try{let n=await e(r.data);return i.close(),n}catch(n){console.warn(n),new xe.Notice(n.toString()),i.close();return}}async createAdvancedSearchModal(t){let e=new Ii(this.plugin,t);return{advancedSearchModalResult:await new Promise(i=>{e.setSubmitCallback(n=>i({code:0,data:n})),e.setCloseCallback(n=>{n&&i({code:3,error:n}),i({code:2})}),e.open()}),advancedSearchModal:e}}async openAdvancedSearchModal(t,e){let{advancedSearchModalResult:r,advancedSearchModal:i}=await this.createAdvancedSearch
${this.settings.useCustomYamlStringifier?ei.toYaml(i):(0,ne.stringifyYaml)(i)}---
`+n,n}async attachFile(e,r,i){if(!i)return{fileMetadata:e,fileContent:r};let n=this.getMetadataFromFileCache(i);e=Object.assign(n,e);let a=await this.app.vault.read(i),s=new RegExp(this.frontMatterRexExpPattern);return a=a.replace(s,""),a=a.startsWith(`
`)?a.substring(1):a,r+=a,{fileMetadata:e,fileContent:r}}async attachTemplate(e,r,i){if(!i)return{fileMetadata:e,fileContent:r};let n=this.getMetaDataFromFileContent(i);e=Object.assign(n,e);let a=new RegExp(this.frontMatterRexExpPattern),s=i.replace(a,"");return r+=s,{fileMetadata:e,fileContent:r}}getMetaDataFromFileContent(e){let r,n=new RegExp(this.frontMatterRexExpPattern).exec(e);if(!n)return{};let a=n[0];return a?(a=a.substring(4),a=a.substring(0,a.length-3),r=(0,ne.parseYaml)(a),r||(r={}),console.debug("MDB | metadata read from file content",r),r):{}}getMetadataFromFileCache(e){let r=this.app.metadataCache.getFileCache(e).frontmatter;return r?(r=Object.assign({},r),delete r.position):r={},r}async createNote(e,r,i){var p;let n=(p=i.folder)!=null?p:this.app.vault.getAbstractFileByPath("/");e=io(e);let a=`${n.path}/${e}.md`,s=this.app.vault.getAbstractFileByPath(a);s&&await this.app.vault.delete(s);let l=await this.app.vault.create(a,r);if(console.debug(`MDB | created new file at ${a}`),i.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"}})}}async updateActiveNote(e=!1){let r=this.app.workspace.getActiveFile();if(!r)throw new Error("MDB | there is no active note");let i=this.getMetadataFromFileCache(r);if(i=this.modelPropertyMapper.convertObjectBack(i),console.debug("MDB | read metadata",i),!(i!=null&&i.type)||!(i!=null&&i.dataSource)||!(i!=null&&i.id))throw new Error("MDB | active note is not a Media DB entry or is missing metadata");let n=this.mediaTypeManager.createMediaTypeModelFromMediaType(i,i.type),a=await this.apiManager.queryDetailedInfoById(i.id,i.dataSource);a&&(a=Object.assign(n,a.getWithOutUserData()),console.debug("MDB | deleting old entry"),e?await this.createMediaDbNoteFromModel(a,{attachFile:r,folder:r.parent,openNote:!0}):await this.createMediaDbNoteFromModel(a,{attachTemplate:!0,folder:r.parent,openNote:!0}))}async createEntriesFromFolder(e){let r=[],i=!1,{selectedAPI:n,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 e.children)if(l instanceof ne.TFile){let p=l;if(i){r.push({filePath:p.path,error:"user canceled"});continue}let c=this.getMetadataFromFileCache(p)[a];if(!c){r.push({filePath:p.path,error:`metadata field '${a}' not found or empty`});continue}let u=[];try{u=await this.apiManager.query(c,[n])}catch(f){r.push({filePath:p.path,error:f.toString()});continue}if(!u||u.length===0){r.push({filePath:p.path,error:"no search results"});continue}let{selectModalResult:m,selectModal:M}=await this.modalHelper.createSelectModal({elements:u,skipButton:!0,modalTitle:`Results for '${c}'`});if(m.code===3){r.push({filePath:p.path,error:m.error.message}),M.close();continue}if(m.code===2){r.push({filePath:p.path,error:"user canceled"}),M.close(),i=!0;continue}if(m.code===1){r.push({filePath:p.path,error:"user skipped"}),M.close();continue}if(m.data.selected.length===0){r.push({filePath:p.path,error:"no search results selected"});continue}let g=await this.queryDetails(m.data.selected);await this.createMediaDbNotes(g,s?p:null),M.close()}r.length>0&&await this.createErroredFilesReport(r)}async createErroredFilesReport(e){let r=`MDB - bulk import error report ${no(new Date)}`,i=`${r}.md`,n=[["file","error"]].concat(e.map(s=>[s.filePath,s.error])),a=`# ${r}
${ro(n)}`;await this.app.vault.create(i,a)}async loadSettings(){let e=await this.loadData(),r=Lo(this),i=Object.assign({},r,e),n=[];for(let a of r.propertyMappingModels){let s=i.propertyMappingModels.find(l=>l.type===a.type);if(s===void 0)n.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))}n.push(new Ft(s.type,l))}}i.propertyMappingModels=n,this.settings=i}async saveSettings(){this.mediaTypeManager.updateTemplates(this.settings),this.mediaTypeManager.updateFolders(this.settings),this.dateFormatter.setFormat(this.settings.customDateFormat),await this.saveData(this.settings)}};