diff --git a/Dockerfile b/Dockerfile index 3faa19c..3060233 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,6 +5,10 @@ ENV DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get install -y ffmpeg liquidsoap +RUN curl -fsSL https://deno.land/install.sh | sh +ENV DENO_INSTALL="/$HOME/.deno" +ENV PATH="$DENO_INSTALL/bin:$PATH" + WORKDIR / RUN adduser zambla @@ -13,13 +17,10 @@ COPY radio.liq /opt/radio.liq COPY yt_sync.py /opt COPY ultrasync.sh /opt COPY je_te_met_en_pls.py /opt +COPY met_extractor.py /opt COPY www /var/www -RUN curl -fsSL https://deno.land/install.sh | sh -ENV DENO_INSTALL="/$HOME/.deno" -ENV PATH="$DENO_INSTALL/bin:$PATH" - -RUN chmod +x /opt/yt_sync.py /opt/ultrasync.sh /opt/je_te_met_en_pls.py +RUN chmod +x /opt/yt_sync.py /opt/ultrasync.sh /opt/je_te_met_en_pls.py /opt/met_extractor.py RUN mkdir -p /songs /jingles /air-support /var/log/liquidsoap diff --git a/je_te_met_en_pls.py b/je_te_met_en_pls.py index af6c190..81aeecd 100755 --- a/je_te_met_en_pls.py +++ b/je_te_met_en_pls.py @@ -3,6 +3,7 @@ import glob import os import sys import subprocess +import json from pathlib import Path @@ -30,12 +31,17 @@ def get_song_length(file: Path) -> float: return -1 -def generate_pls(directory: str, output_file: str | None = None) -> None: +def generate_playlist( + directory: Path, + pls_file: Path | None = None, + json_file: Path | None = None, +) -> None: """Generate a .pls playlist file from all audio files in a directory. Args: directory: Path to directory containing audio files - output_file: Path to output .pls file (default: directory/playlist.pls) + pls_file: Path to output .pls file (default: directory/playlist.pls) + json_file: Path to output .json file (default: directory/playlist.json) """ if not os.path.isdir(directory): print(f"Error: Directory '{directory}' does not exist") @@ -58,10 +64,15 @@ def generate_pls(directory: str, output_file: str | None = None) -> None: audio_files.sort() # Determine output file path - if output_file is None: - output_file = os.path.join(directory, "playlist.pls") + if pls_file is None: + pls_file = directory / "playlist.pls" - # Generate .pls content + if json_file is None: + json_file = directory / "playlist.json" + + json_content = {} + + # Generate output content pls_content = ["[playlist]"] pls_content.append(f"NumberOfEntries={len(audio_files)}") pls_content.append("") @@ -69,28 +80,48 @@ def generate_pls(directory: str, output_file: str | None = None) -> None: for idx, path in enumerate(audio_files, start=1): file = Path(path) + title = file.stem.replace('_', ' ') + duration = get_song_length(file) + pls_content.append(f"File{idx}={file.absolute()}") - pls_content.append(f"Title{idx}={file.stem.replace('_', ' ')}") - pls_content.append(f"Length{idx}={get_song_length(file)}") + pls_content.append(f"Title{idx}={title}") + pls_content.append(f"Length{idx}={duration}") pls_content.append("") + json_content[str(file.absolute())] = { + "index": idx, + "file": str(file.absolute()), + "title": title, + "duration": duration, + } + pls_content.append("Version=2") # Write to file - with open(output_file, "w") as f: + with open(pls_file, "w") as f: f.write("\n".join(pls_content)) - print(f"Generated '{output_file}' with {len(audio_files)} entries") + with open(json_file, "w") as f: + json.dump(json_content, f) + + print(f"Generated '{pls_file}' with {len(audio_files)} entries") + print(f"Generated '{json_file}' with {len(audio_files)} entries") if __name__ == "__main__": if len(sys.argv) < 2: - print("Usage: je_te_met_en_pls.py [output_file.pls]") + print( + "Usage: je_te_met_en_pls.py [output_file.pls] [output_file.json]" + ) print("Example: je_te_met_en_pls.py /songs") print("Example: je_te_met_en_pls.py /songs /tmp/my_playlist.pls") + print( + "Example: je_te_met_en_pls.py /songs /tmp/my_playlist.pls /tmp/my_playlist.json" + ) sys.exit(1) directory = sys.argv[1] - output_file = sys.argv[2] if len(sys.argv) > 2 else None + pls_file = Path(sys.argv[2]) if len(sys.argv) > 2 else None + json_file = Path(sys.argv[3]) if len(sys.argv) > 3 else None - generate_pls(directory, output_file) + generate_playlist(Path(directory), pls_file, json_file) diff --git a/met_extractor.py b/met_extractor.py new file mode 100755 index 0000000..75a0c03 --- /dev/null +++ b/met_extractor.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +import sys +import json + +if len(sys.argv) < 2: + print( + "Usage: met_etractor.py " + ) + print("Example: met_extractor.py /tmp/my_playlist.json key") + sys.exit(1) + +with open(sys.argv[1], "r", encoding="utf-8") as f: + met = json.load(f) + print(json.dumps(met.get(sys.argv[2], {}))) diff --git a/radio.liq b/radio.liq index b9f6e1d..3052dfa 100644 --- a/radio.liq +++ b/radio.liq @@ -10,6 +10,10 @@ hostname = environment.get(default="localhost", "HOSTNAME") port = int_of_string(environment.get(default="8000", "PORT")) +folder_songs = "/songs" +folder_jingles = "/jingles" +folder_air_support = "/air-support" + # Log configuration log.file.path := "/var/log/liquidsoap/radio-bullshit.log" log.level := 3 @@ -23,7 +27,7 @@ songs = playlist( mode="randomize", reload=60, reload_mode="watch", - "/songs/playlist.pls" + "#{folder_songs}/playlist.pls" ) # Jingles playlist @@ -31,7 +35,7 @@ jingles = playlist( mode="randomize", reload=60, reload_mode="watch", - "/jingles/playlist.pls" + "#{folder_jingles}/playlist.pls" ) # Air support (fallback audio when nothing else is available) @@ -39,16 +43,54 @@ air_support = mksafe( playlist( mode="randomize", reload_mode="watch", - "/air-support/playlist.pls" + "#{folder_air_support}/playlist.pls" ) ) +# ============================================================================ +# METADATA UPDATE +# ============================================================================ + +def enrich_metadata(folder, m) + entry = process.read("/opt/met_extractor.py #{folder}/playlist.json '#{metadata.filename(m)}'") + let json.parse (entry : + { + index: int?, + file: string?, + title: string?, + duration: float? + } + ) = entry + [("title", "#{entry.title}")] +end + +songs = map_metadata( + fun (m) -> begin + enrich_metadata(folder_songs, m) + end, + songs +) + +jingles = map_metadata( + fun (m) -> begin + enrich_metadata(folder_jingles, m) + end, + jingles +) + +air_support = map_metadata( + fun (m) -> begin + enrich_metadata(folder_air_support, m) + end, + air_support +) + # ============================================================================ # ALTERNATING LOGIC # ============================================================================ # Alternate between songs and jingles: play 1 jingle, then 4 songs -# This creates a pattern: jingle, song, song, song, song, jingle, ... +# This creates a pattern: jingle, song, jingle, ... radio = rotate( weights=[1, 1], [jingles, songs] @@ -112,14 +154,13 @@ harbor.http.register( ) # Status endpoint (JSON) -# harbor.http.register( -# port=port, -# method="GET", -# "/status.json", -# fun (_, response) -> begin -# status = '{"status":"online","stream":"Radio Bullshit","mount":"/radio-bullshit"}' -# response.json(parse_json(status)) -# end -# ) +harbor.http.register( + port=port, + method="GET", + "/status.json", + fun (_, response) -> begin + response.json(radio.last_metadata() ?? [("status", "down")]) + end +) log("Radio Bullshit is now streaming on http://#{hostname}:#{port}/radio-bullshit") diff --git a/www/index.html b/www/index.html index 2eaef27..7fb4dc2 100644 --- a/www/index.html +++ b/www/index.html @@ -1,16 +1,28 @@ + Radio bullshit, la radio du paradis ! - - +
+

+ +

  • VLC Stream
  • @@ -19,4 +31,11 @@

    + \ No newline at end of file diff --git a/www/static/alpine.min.js b/www/static/alpine.min.js new file mode 100644 index 0000000..b4300db --- /dev/null +++ b/www/static/alpine.min.js @@ -0,0 +1,5 @@ +(()=>{var nt=!1,it=!1,G=[],ot=-1;function Ut(e){In(e)}function In(e){G.includes(e)||G.push(e),$n()}function Wt(e){let t=G.indexOf(e);t!==-1&&t>ot&&G.splice(t,1)}function $n(){!it&&!nt&&(nt=!0,queueMicrotask(Ln))}function Ln(){nt=!1,it=!0;for(let e=0;ee.effect(t,{scheduler:r=>{st?Ut(r):r()}}),at=e.raw}function ct(e){N=e}function Yt(e){let t=()=>{};return[n=>{let i=N(n);return e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(o=>o())}),e._x_effects.add(i),t=()=>{i!==void 0&&(e._x_effects.delete(i),F(i))},i},()=>{t()}]}function Oe(e,t){let r=!0,n,i=N(()=>{let o=e();JSON.stringify(o),r?n=o:queueMicrotask(()=>{t(o,n),n=o}),r=!1});return()=>F(i)}var Xt=[],Zt=[],Qt=[];function er(e){Qt.push(e)}function re(e,t){typeof t=="function"?(e._x_cleanups||(e._x_cleanups=[]),e._x_cleanups.push(t)):(t=e,Zt.push(t))}function Re(e){Xt.push(e)}function Te(e,t,r){e._x_attributeCleanups||(e._x_attributeCleanups={}),e._x_attributeCleanups[t]||(e._x_attributeCleanups[t]=[]),e._x_attributeCleanups[t].push(r)}function lt(e,t){e._x_attributeCleanups&&Object.entries(e._x_attributeCleanups).forEach(([r,n])=>{(t===void 0||t.includes(r))&&(n.forEach(i=>i()),delete e._x_attributeCleanups[r])})}function tr(e){for(e._x_effects?.forEach(Wt);e._x_cleanups?.length;)e._x_cleanups.pop()()}var ut=new MutationObserver(mt),ft=!1;function pe(){ut.observe(document,{subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0}),ft=!0}function dt(){jn(),ut.disconnect(),ft=!1}var de=[];function jn(){let e=ut.takeRecords();de.push(()=>e.length>0&&mt(e));let t=de.length;queueMicrotask(()=>{if(de.length===t)for(;de.length>0;)de.shift()()})}function m(e){if(!ft)return e();dt();let t=e();return pe(),t}var pt=!1,Ce=[];function rr(){pt=!0}function nr(){pt=!1,mt(Ce),Ce=[]}function mt(e){if(pt){Ce=Ce.concat(e);return}let t=[],r=new Set,n=new Map,i=new Map;for(let o=0;o{s.nodeType===1&&s._x_marker&&r.add(s)}),e[o].addedNodes.forEach(s=>{if(s.nodeType===1){if(r.has(s)){r.delete(s);return}s._x_marker||t.push(s)}})),e[o].type==="attributes")){let s=e[o].target,a=e[o].attributeName,c=e[o].oldValue,l=()=>{n.has(s)||n.set(s,[]),n.get(s).push({name:a,value:s.getAttribute(a)})},u=()=>{i.has(s)||i.set(s,[]),i.get(s).push(a)};s.hasAttribute(a)&&c===null?l():s.hasAttribute(a)?(u(),l()):u()}i.forEach((o,s)=>{lt(s,o)}),n.forEach((o,s)=>{Xt.forEach(a=>a(s,o))});for(let o of r)t.some(s=>s.contains(o))||Zt.forEach(s=>s(o));for(let o of t)o.isConnected&&Qt.forEach(s=>s(o));t=null,r=null,n=null,i=null}function Me(e){return k(B(e))}function D(e,t,r){return e._x_dataStack=[t,...B(r||e)],()=>{e._x_dataStack=e._x_dataStack.filter(n=>n!==t)}}function B(e){return e._x_dataStack?e._x_dataStack:typeof ShadowRoot=="function"&&e instanceof ShadowRoot?B(e.host):e.parentNode?B(e.parentNode):[]}function k(e){return new Proxy({objects:e},Fn)}var Fn={ownKeys({objects:e}){return Array.from(new Set(e.flatMap(t=>Object.keys(t))))},has({objects:e},t){return t==Symbol.unscopables?!1:e.some(r=>Object.prototype.hasOwnProperty.call(r,t)||Reflect.has(r,t))},get({objects:e},t,r){return t=="toJSON"?Bn:Reflect.get(e.find(n=>Reflect.has(n,t))||{},t,r)},set({objects:e},t,r,n){let i=e.find(s=>Object.prototype.hasOwnProperty.call(s,t))||e[e.length-1],o=Object.getOwnPropertyDescriptor(i,t);return o?.set&&o?.get?o.set.call(n,r)||!0:Reflect.set(i,t,r)}};function Bn(){return Reflect.ownKeys(this).reduce((t,r)=>(t[r]=Reflect.get(this,r),t),{})}function ne(e){let t=n=>typeof n=="object"&&!Array.isArray(n)&&n!==null,r=(n,i="")=>{Object.entries(Object.getOwnPropertyDescriptors(n)).forEach(([o,{value:s,enumerable:a}])=>{if(a===!1||s===void 0||typeof s=="object"&&s!==null&&s.__v_skip)return;let c=i===""?o:`${i}.${o}`;typeof s=="object"&&s!==null&&s._x_interceptor?n[o]=s.initialize(e,c,o):t(s)&&s!==n&&!(s instanceof Element)&&r(s,c)})};return r(e)}function Ne(e,t=()=>{}){let r={initialValue:void 0,_x_interceptor:!0,initialize(n,i,o){return e(this.initialValue,()=>zn(n,i),s=>ht(n,i,s),i,o)}};return t(r),n=>{if(typeof n=="object"&&n!==null&&n._x_interceptor){let i=r.initialize.bind(r);r.initialize=(o,s,a)=>{let c=n.initialize(o,s,a);return r.initialValue=c,i(o,s,a)}}else r.initialValue=n;return r}}function zn(e,t){return t.split(".").reduce((r,n)=>r[n],e)}function ht(e,t,r){if(typeof t=="string"&&(t=t.split(".")),t.length===1)e[t[0]]=r;else{if(t.length===0)throw error;return e[t[0]]||(e[t[0]]={}),ht(e[t[0]],t.slice(1),r)}}var ir={};function y(e,t){ir[e]=t}function K(e,t){let r=Hn(t);return Object.entries(ir).forEach(([n,i])=>{Object.defineProperty(e,`$${n}`,{get(){return i(t,r)},enumerable:!1})}),e}function Hn(e){let[t,r]=_t(e),n={interceptor:Ne,...t};return re(e,r),n}function or(e,t,r,...n){try{return r(...n)}catch(i){ie(i,e,t)}}function ie(...e){return sr(...e)}var sr=Kn;function ar(e){sr=e}function Kn(e,t,r=void 0){e=Object.assign(e??{message:"No error message given."},{el:t,expression:r}),console.warn(`Alpine Expression Error: ${e.message} + +${r?'Expression: "'+r+`" + +`:""}`,t),setTimeout(()=>{throw e},0)}var oe=!0;function De(e){let t=oe;oe=!1;let r=e();return oe=t,r}function T(e,t,r={}){let n;return x(e,t)(i=>n=i,r),n}function x(...e){return cr(...e)}var cr=xt;function lr(e){cr=e}var ur;function fr(e){ur=e}function xt(e,t){let r={};K(r,e);let n=[r,...B(e)],i=typeof t=="function"?Vn(n,t):Un(n,t,e);return or.bind(null,e,t,i)}function Vn(e,t){return(r=()=>{},{scope:n={},params:i=[],context:o}={})=>{if(!oe){me(r,t,k([n,...e]),i);return}let s=t.apply(k([n,...e]),i);me(r,s)}}var gt={};function qn(e,t){if(gt[e])return gt[e];let r=Object.getPrototypeOf(async function(){}).constructor,n=/^[\n\s]*if.*\(.*\)/.test(e.trim())||/^(let|const)\s/.test(e.trim())?`(async()=>{ ${e} })()`:e,o=(()=>{try{let s=new r(["__self","scope"],`with (scope) { __self.result = ${n} }; __self.finished = true; return __self.result;`);return Object.defineProperty(s,"name",{value:`[Alpine] ${e}`}),s}catch(s){return ie(s,t,e),Promise.resolve()}})();return gt[e]=o,o}function Un(e,t,r){let n=qn(t,r);return(i=()=>{},{scope:o={},params:s=[],context:a}={})=>{n.result=void 0,n.finished=!1;let c=k([o,...e]);if(typeof n=="function"){let l=n.call(a,n,c).catch(u=>ie(u,r,t));n.finished?(me(i,n.result,c,s,r),n.result=void 0):l.then(u=>{me(i,u,c,s,r)}).catch(u=>ie(u,r,t)).finally(()=>n.result=void 0)}}}function me(e,t,r,n,i){if(oe&&typeof t=="function"){let o=t.apply(r,n);o instanceof Promise?o.then(s=>me(e,s,r,n)).catch(s=>ie(s,i,t)):e(o)}else typeof t=="object"&&t instanceof Promise?t.then(o=>e(o)):e(t)}function dr(...e){return ur(...e)}function pr(e,t,r={}){let n={};K(n,e);let i=[n,...B(e)],o=k([r.scope??{},...i]),s=r.params??[];if(t.includes("await")){let a=Object.getPrototypeOf(async function(){}).constructor,c=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(async()=>{ ${t} })()`:t;return new a(["scope"],`with (scope) { let __result = ${c}; return __result }`).call(r.context,o)}else{let a=/^[\n\s]*if.*\(.*\)/.test(t.trim())||/^(let|const)\s/.test(t.trim())?`(()=>{ ${t} })()`:t,l=new Function(["scope"],`with (scope) { let __result = ${a}; return __result }`).call(r.context,o);return typeof l=="function"&&oe?l.apply(o,s):l}}var wt="x-";function C(e=""){return wt+e}function mr(e){wt=e}var ke={};function d(e,t){return ke[e]=t,{before(r){if(!ke[r]){console.warn(String.raw`Cannot find directive \`${r}\`. \`${e}\` will use the default order of execution`);return}let n=J.indexOf(r);J.splice(n>=0?n:J.indexOf("DEFAULT"),0,e)}}}function hr(e){return Object.keys(ke).includes(e)}function _e(e,t,r){if(t=Array.from(t),e._x_virtualDirectives){let o=Object.entries(e._x_virtualDirectives).map(([a,c])=>({name:a,value:c})),s=Et(o);o=o.map(a=>s.find(c=>c.name===a.name)?{name:`x-bind:${a.name}`,value:`"${a.value}"`}:a),t=t.concat(o)}let n={};return t.map(xr((o,s)=>n[o]=s)).filter(br).map(Gn(n,r)).sort(Jn).map(o=>Wn(e,o))}function Et(e){return Array.from(e).map(xr()).filter(t=>!br(t))}var yt=!1,he=new Map,_r=Symbol();function gr(e){yt=!0;let t=Symbol();_r=t,he.set(t,[]);let r=()=>{for(;he.get(t).length;)he.get(t).shift()();he.delete(t)},n=()=>{yt=!1,r()};e(r),n()}function _t(e){let t=[],r=a=>t.push(a),[n,i]=Yt(e);return t.push(i),[{Alpine:z,effect:n,cleanup:r,evaluateLater:x.bind(x,e),evaluate:T.bind(T,e)},()=>t.forEach(a=>a())]}function Wn(e,t){let r=()=>{},n=ke[t.type]||r,[i,o]=_t(e);Te(e,t.original,o);let s=()=>{e._x_ignore||e._x_ignoreSelf||(n.inline&&n.inline(e,t,i),n=n.bind(n,e,t,i),yt?he.get(_r).push(n):n())};return s.runCleanups=o,s}var Pe=(e,t)=>({name:r,value:n})=>(r.startsWith(e)&&(r=r.replace(e,t)),{name:r,value:n}),Ie=e=>e;function xr(e=()=>{}){return({name:t,value:r})=>{let{name:n,value:i}=yr.reduce((o,s)=>s(o),{name:t,value:r});return n!==t&&e(n,t),{name:n,value:i}}}var yr=[];function se(e){yr.push(e)}function br({name:e}){return wr().test(e)}var wr=()=>new RegExp(`^${wt}([^:^.]+)\\b`);function Gn(e,t){return({name:r,value:n})=>{r===n&&(n="");let i=r.match(wr()),o=r.match(/:([a-zA-Z0-9\-_:]+)/),s=r.match(/\.[^.\]]+(?=[^\]]*$)/g)||[],a=t||e[r]||r;return{type:i?i[1]:null,value:o?o[1]:null,modifiers:s.map(c=>c.replace(".","")),expression:n,original:a}}}var bt="DEFAULT",J=["ignore","ref","data","id","anchor","bind","init","for","model","modelable","transition","show","if",bt,"teleport"];function Jn(e,t){let r=J.indexOf(e.type)===-1?bt:e.type,n=J.indexOf(t.type)===-1?bt:t.type;return J.indexOf(r)-J.indexOf(n)}function Y(e,t,r={}){e.dispatchEvent(new CustomEvent(t,{detail:r,bubbles:!0,composed:!0,cancelable:!0}))}function P(e,t){if(typeof ShadowRoot=="function"&&e instanceof ShadowRoot){Array.from(e.children).forEach(i=>P(i,t));return}let r=!1;if(t(e,()=>r=!0),r)return;let n=e.firstElementChild;for(;n;)P(n,t,!1),n=n.nextElementSibling}function E(e,...t){console.warn(`Alpine Warning: ${e}`,...t)}var Er=!1;function vr(){Er&&E("Alpine has already been initialized on this page. Calling Alpine.start() more than once can cause problems."),Er=!0,document.body||E("Unable to initialize. Trying to load Alpine before `` is available. Did you forget to add `defer` in Alpine's `