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.

65 lines
118 KiB

3 years ago
/*
11 months ago
-------------------------------------------
5 months ago
Media DB - Release Build
11 months ago
-------------------------------------------
5 months ago
By: Moritz Jung (https://www.moritzjung.dev)
4 months ago
Time: Fri, 05 Jul 2024 12:27:45 GMT
Version: 0.7.2
11 months ago
-------------------------------------------
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
5 months ago
-------------------------------------------
MIT License
Copyright (c) 2024 Moritz Jung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 years ago
*/
4 months ago
var ai=Object.defineProperty;var Yn=Object.getOwnPropertyDescriptor;var zn=Object.getOwnPropertyNames;var Kn=Object.prototype.hasOwnProperty;var Xn=(r,e,t)=>e in r?ai(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Jn=(r,e)=>{for(var t in e)ai(r,t,{get:e[t],enumerable:!0})},Zn=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of zn(e))!Kn.call(r,n)&&n!==t&&ai(r,n,{get:()=>e[n],enumerable:!(i=Yn(e,n))||i.enumerable});return r};var Qn=r=>Zn(ai({},"__esModule",{value:!0}),r);var K=(r,e,t)=>(Xn(r,typeof e!="symbol"?e+"":e,t),t);var da={};Jn(da,{default:()=>zi});module.exports=Qn(da);var z=require("obsidian");var E=require("obsidian");var cn=require("obsidian");var dn=require("obsidian");var A="top",H="bottom",W="right",B="left",si="auto",We=[A,H,W,B],$e="start",Ke="end",Nr="clippingParents",li="viewport",bt="popper",Ar="reference",Ki=We.reduce(function(r,e){return r.concat([e+"-"+$e,e+"-"+Ke])},[]),pi=[].concat(We,[si]).reduce(function(r,e){return r.concat([e,e+"-"+$e,e+"-"+Ke])},[]),eo="beforeRead",to="read",io="afterRead",ro="beforeMain",no="main",oo="afterMain",ao="beforeWrite",so="write",lo="afterWrite",Br=[eo,to,io,ro,no,oo,ao,so,lo];function X(r){return r?(r.nodeName||"").toLowerCase():null}function F(r){if(r==null)return window;if(r.toString()!=="[object Window]"){var e=r.ownerDocument;return e&&e.defaultView||window}return r}function de(r){var e=F(r).Element;return r instanceof e||r instanceof Element}function V(r){var e=F(r).HTMLElement;return r instanceof e||r instanceof HTMLElement}function wt(r){if(typeof ShadowRoot=="undefined")return!1;var e=F(r).ShadowRoot;return r instanceof e||r instanceof ShadowRoot}function po(r){var e=r.state;Object.keys(e.elements).forEach(function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},o=e.elements[t];!V(o)||!X(o)||(Object.assign(o.style,i),Object.keys(n).forEach(function(a){var s=n[a];s===!1?o.removeAttribute(a):o.setAttribute(a,s===!0?"":s)}))})}function co(r){var e=r.state,t={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,t.popper),e.styles=t,e.elements.arrow&&Object.assign(e.elements.arrow.style,t.arrow),function(){Object.keys(e.elements).forEach(function(i){var n=e.elements[i],o=e.attributes[i]||{},a=Object.keys(e.styles.hasOwnProperty(i)?e.styles[i]:t[i]),s=a.reduce(function(l,p){return l[p]="",l},{});!V(n)||!X(n)||(Object.assign(n.style,s),Object.keys(o).forEach(function(l){n.removeAttribute(l)}))})}}var Ir={name:"applyStyles",enabled:!0,phase:"write",fn:po,effect:co,requires:["computeStyles"]};function J(r){return r.split("-")[0]}var he=Math.max,Xe=Math.min,Re=Math.round;function xt(){var r=navigator.userAgentData;return r!=null&&r.brands&&Array.isArray(r.brands)?r.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function jt(){return!/^((?!chrome|android).)*safari/i.test(xt())}function ce(r,e,t){e===void 0&&(e=!1),t===void 0&&(t=!1);var i=r.getBoundingClientRect(),n=1,o=1;e&&V(r)&&(n=r.offsetWidth>0&&Re(i.width)/r.offsetWidth||1,o=r.offsetHeight>0&&Re(i.height)/r.offsetHeight||1);var a=de(r)?F(r):window,s=a.visualViewport,l=!jt()&&t,p=(i.left+(l&&s?s.offsetLeft:0))/n,d=(i.top+(l&&s?s.offsetTop:0))/o,c=i.width/n,f=i.height/o;return{width:c,height:f,top:d,right:p+c,bottom:d+f,left:p,x:p,y:d}}function Je(r){var e=ce(r),t=r.offsetWidth,i=r.offsetHeight;return Math.abs(e.width-t)<=1&&(t=e.width),Math.abs(e.height-i)<=1&&(i=e.height),{x:r.offsetLeft,y:r.offsetTop,width:t,height:i}}function qt(r,e){var t=e.getRootNode&&e.getRootNode();if(r.contains(e))return!0;if(t&&wt(t)){var i=e;do{if(i&&r.isSameNode(i))return!0;i=i.parentNode||i.host}while(i)}return!1}function ae(r){return F(r).getComputedStyle(r)}function Xi(r){return["table","td","th"].indexOf(X(r))>=0}function ie(r){return((de(r)?r.ownerDocument:r.document)||window.document).documentElement}function Oe(r){return X(r)==="html"?r:r.assignedSlot||r.parentNode||(wt(r)?r.host:null)||ie(r)}function Lr(r){return!V(r)||ae(r).position==="fixed"?null:r.of
5 months ago
`):"{{ 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 }}":`{{ INVALID TEMPLATE TAG - unknown operator ${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+=`
`,o===0){n+="|";for(let a=0;a<t;a++)n+=" "+"-".repeat(i[a])+" |";n+=`
4 months ago
`}}return n}function sn(r){return createFragment(e=>e.createDiv().innerHTML=r)}function No(r){return`${r.getMonth()+1}-${r.getDate()}-${r.getFullYear()}`}function Ao(r){return`${r.getHours()}-${r.getMinutes()}-${r.getSeconds()}`}function ln(r){return`${No(r)} ${Ao(r)}`}function mi(r,e){return(r%e+e)%e}function fr(r){return r.charAt(0).toUpperCase()+r.slice(1)}var rt=class extends Error{constructor(e){super(e)}},Yt=class extends Error{constructor(e){super(e)}};function $(r,e,t){for(let i in r)r[i]=e.hasOwnProperty(i)?e[i]:t[i]}function zt(r){return r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b([A-Z]+)([A-Z])([a-z])/,"$1 $2$3").replace(/^./,function(e){return e.toUpperCase()})}function hr(r){return!!r.plugins.plugins["templater-obsidian"]}async function pn(r,e){let t=r.plugins.plugins["templater-obsidian"];t&&!(t!=null&&t.settings.trigger_on_file_creation)&&await t.templater.overwrite_file_commands(e)}var gr=class{constructor(e,t,i){this.owner=e,this.containerEl=t,t.on("click",".suggestion-item",this.onSuggestionClick.bind(this)),t.on("mousemove",".suggestion-item",this.onSuggestionMouseover.bind(this)),i.register([],"ArrowUp",n=>{if(!n.isComposing)return this.setSelectedItem(this.selectedItem-1,!0),!1}),i.register([],"ArrowDown",n=>{if(!n.isComposing)return this.setSelectedItem(this.selectedItem+1,!0),!1}),i.register([],"Enter",n=>{if(!n.isComposing)return this.useSelectedItem(n),!1})}onSuggestionClick(e,t){e.preventDefault();let i=this.suggestions.indexOf(t);this.setSelectedItem(i,!1),this.useSelectedItem(e)}onSuggestionMouseover(e,t){let i=this.suggestions.indexOf(t);this.setSelectedItem(i,!1)}setSuggestions(e){this.containerEl.empty();let t=[];e.forEach(i=>{let n=this.containerEl.createDiv("suggestion-item");this.owner.renderSuggestion(i,n),t.push(n)}),this.values=e,this.suggestions=t,this.setSelectedItem(0,!1)}useSelectedItem(e){let t=this.values[this.selectedItem];t&&this.owner.selectSuggestion(t,e)}setSelectedItem(e,t){let i=this.suggestions.length>0?nn(e,this.suggestions.length):0,n=this.suggestions[this.selectedItem],o=this.suggestions[i];n==null||n.removeClass("is-selected"),o==null||o.addClass("is-selected"),this.selectedItem=i,t&&o.scrollIntoView(!1)}},St=class{constructor(e,t){this.app=e,this.inputEl=t,this.scope=new dn.Scope,this.suggestEl=createDiv("suggestion-container");let i=this.suggestEl.createDiv("suggestion");this.suggest=new gr(this,i,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",n=>{n.preventDefault()})}onInputChanged(){let e=this.inputEl.value,t=this.getSuggestions(e);t.length>0&&(this.suggest.setSuggestions(t),this.open(this.app.dom.appContainerEl,this.inputEl))}open(e,t){this.app.keymap.pushScope(this.scope),e.appendChild(this.suggestEl),this.popper=lr(t,this.suggestEl,{placement:"bottom-start",modifiers:[{name:"sameWidth",enabled:!0,fn:({state:i,instance:n})=>{let o=`${i.rects.reference.width}px`;i.styles.popper.width!==o&&(i.styles.popper.width=o,n.update())},phase:"beforeWrite",requires:["computeStyles"]}]})}close(){var e;this.app.keymap.popScope(this.scope),this.suggest.setSuggestions([]),(e=this.popper)==null||e.destroy(),this.suggestEl.detach()}};var Me=class extends St{getSuggestions(e){let t=this.app.vault.getAllLoadedFiles(),i=[],n=e.toLowerCase();return t.forEach(o=>{o instanceof cn.TFolder&&o.path.toLowerCase().contains(n)&&i.push(o)}),i}renderSuggestion(e,t){t.setText(e.path)}selectSuggestion(e){this.inputEl.value=e.path,this.inputEl.trigger("input"),this.close()}};var un=require("obsidian"),ve=class extends St{getSuggestions(e){let t=this.app.vault.getAllLoadedFiles(),i=[],n=e.toLowerCase();return t.forEach(o=>{o instanceof un.TFile&&o.name.toLowerCase().contains(n)&&i.push(o)}),i}renderSuggestion(e,t){t.setText(e.path)}selectSuggestion(e){this.inputEl.value=e.path,this.inputEl.trigger("input"),this.close()}};
<p>Choose how metadata fields are mapped to property names. The options are:</p>
<ul>
<li><strong>default</strong>: keep the original name.</li>
<li><strong>remap</strong>: rename the property.</li>
<li><strong>remove</strong>: remove the property entirely.</li>
</ul>
<p>
Don't forget to save your changes using the save button for each individual category.
4 months ago
</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 E.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==="Movie not found!")return[];throw Error(`MDB | Received error from ${this.apiName}:
${JSON.stringify(o,void 0,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,C,x,v,k,P,N,Q,U,ee,_e,le;if(console.log(`MDB | api "${this.apiName}" queried by ID`),!this.plugin.settings.OMDbKey)throw Error(`MDB | API key for ${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:(C=o.Runtime)!=null?C:"unknown",onlineRating:Number.parseFloat((x=o.imdbRating)!=null?x:0),actors:(k=(v=o.Actors)==null?void 0:v.split(", "))!=null?k:[],image:(P=o.Poster)!=null?P:"",released:!0,streamingServices:[],airing:!1,airedFrom:(N=this.plugin.dateFormatter.format(o.Released,this.apiDateFormat))!=null?N:"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,C;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.
5 months ago
`}),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
4 months ago
${a}\`\`\``;try{await He.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"});let i=new He.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 xe=require("obsidian");var Vi=class extends xe.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(let i of Pe)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()}async search(){if(!this.query||this.query.length<3){new xe.Notice("MDB | Query too short");return}let e=this.selectedTypes.filter(t=>t.selected).map(t=>t.name);if(e.length===0){new xe.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 t="Search by title",i=new xe.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(let o of Pe){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(o),cls:"media-db-plugin-list-text"});let l=a.createEl("div",{cls:"media-db-plugin-list-toggle"}),p=new xe.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"}),new xe.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()}};var Gn={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}async createSearchModal(e){let t=new Vi(this.plugin,e);return{searchModalResult:await new Promise(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}}async openSearchModal(e,t){let{searchModalResult:i,searchModal:n}=await this.createSearchModal(e);if(console.debug(`MDB | searchModal closed with code ${i.code}`),i.code==="ERROR"){console.warn(i.error),new Te.Notice(i.error.toString()),n.close();return}if(i.code!=="CLOSE")try{let o=await t(i.data);return n.close(),o}catch(o){console.warn(o),new Te.Notice(o.toString()),n.close();return}}async createAdvancedSearchModal(e){let t=new Ii(this.plugin,e);return{advancedSearchModalResult:await new Promise(n=>{t.setSubmitCallback(o=>n({code:"SUCCESS",data:o})),t
5 months ago
<%* const media = ${JSON.stringify(t)} %>
${(0,z.stringifyYaml)(o)}---
${a}`:a=`---
${(0,z.stringifyYaml)(o)}---
${a}`,a}async generateContentWithCustomFrontMatter(t,i,n){let o=new RegExp(this.frontMatterRexExpPattern),a=this.getMetaDataFromFileContent(n),s=n.replace(o,"");if(i.attachFile){let l=this.app.metadataCache.getFileCache(i.attachFile).frontmatter;s=await this.app.vault.read(i.attachFile),s=s.replace(o,""),s=s.startsWith(`
`)?s.substring(1):s,Object.keys(l).forEach(p=>{let d=l[p];!a[p]&&d&&(a[p]=d)})}return a.id||(a.id=t.id),a.type||(a.type=t.type),a.dataSource||(a.dataSource=t.dataSource),this.settings.enableTemplaterIntegration&&hr(this.app)?s=`---
<%* const media = ${JSON.stringify(t)} %>
${(0,z.stringifyYaml)(a)}---
${s}`:s=`---
${(0,z.stringifyYaml)(a)}---
${s}`,s}async attachFile(t,i,n){if(!n)return{fileMetadata:t,fileContent:i};let o=this.getMetadataFromFileCache(n);t=Object.assign(o,t);let a=await this.app.vault.read(n),s=new RegExp(this.frontMatterRexExpPattern);return a=a.replace(s,""),a=a.startsWith(`
`)?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 | created new file at ${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:`metadata field '${a}' not found or empty`});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:`Results for '${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 - bulk import error report ${ln(new Date)}`,n=`${i}.md`,o=[["file","error"]].concat(t.map(s=>[s.filePath,s.error])),a=`# ${i}
11 months ago
4 months ago
${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 kt(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)}};