Compare commits

...

No commits in common. "main" and "manifest" have entirely different histories.

27 changed files with 60 additions and 2539 deletions

5
.gitignore vendored
View file

@ -1,5 +0,0 @@
**/obj/
**/bin/
artifacts/
smart-playlist/
manifest.json

View file

@ -1,77 +0,0 @@
using System.Diagnostics;
using Jellyfin.Plugin.SmartPlaylist.Lisp;
namespace Jellyfin.Plugin.SmartPlaylist.Lisp.Compiler {
public class Parser {
private StringTokenStream _sts;
public Parser(StringTokenStream tokens) {
_sts = tokens;
}
public Parser(string s) {
_sts = StringTokenStream.generate(s);
}
public Expression parse() {
Token<string> token = _sts.Get();
switch (token) {
case GroupingToken gt:
return parse_grouping(gt, gt.closing_value);
case AtomToken at:
return parse_atom(at);
case SpaceToken sp:
return parse();
}
return parse();
}
Expression parse_string(GroupingToken start, GroupingToken? end) {
Debug.Assert(end != null);
Debug.Assert(start.value == end.value);
Debug.Assert("\"".Contains(start.value));
string r = "";
while (_sts.Available() > 0) {
Token<string> t = _sts.Get();
if (t.value == end.value) {
break;
}
r += t.value;
}
_sts.Commit();
return new String(r);
}
Expression parse_grouping(GroupingToken start, GroupingToken? end) {
Debug.Assert(end != null);
if ("\"".Contains(start.value)) {
return parse_string(start, end);
}
IList<Expression> expressions = new List<Expression>();
while (_sts.Available() > 0) {
Token<string> t = _sts.Get();
if (t.value == end.value) {
_sts.Commit();
break;
}
_sts.Rewind(1);
expressions.Add(parse());
}
return Cons.FromList(expressions);
}
Expression parse_atom(AtomToken at) {
int parsed_value;
if (int.TryParse(at.value, out parsed_value)) {
_sts.Commit();
return new Integer(parsed_value);
}
if (at.value.Equals("t")) {
return Boolean.TRUE;
}
if (at.value.Equals("nil")) {
return Boolean.FALSE;
}
_sts.Commit();
return new Symbol(at.value);
}
}
}

View file

@ -1,130 +0,0 @@
using System.Reflection;
using Jellyfin.Plugin.SmartPlaylist.Util;
namespace Jellyfin.Plugin.SmartPlaylist.Lisp.Compiler {
public interface IToken<T> {
T value { get; }
abstract static IToken<T>? take<E>(E program);
}
public abstract class Token<T>: IToken<T> , IEquatable<Token<T>> {
protected readonly T _value;
protected Token(T value) {
_value = value;
}
public T value { get => _value; }
public static IToken<T>? take<E>(E program) {
throw new NotImplementedException("Subclass this class");
}
public bool Equals(Token<T>? b) {
return b != null && _value != null && _value.Equals(b._value);
}
}
class SpaceToken : Token<string> {
private SpaceToken(string value) : base(value) {}
private static IToken<string>? take(CharStream program) {
string spaces = " \n";
if (program.Available() == 0) {
return null;
}
var t = program.Get();
if (spaces.Contains(t)) {
return new SpaceToken(t.ToString());
}
return null;
}
}
class GroupingToken: Token<string> {
private GroupingToken(string value) : base(value) {}
private static IToken<string>? take(CharStream program) {
if (program.Available() == 0) {
return null;
}
char t = program.Get();
if ("()\"".Contains(t)) {
return new GroupingToken(t.ToString());
}
return null;
}
private GroupingToken? _closing_value() {
if (_value == "(") {
return new GroupingToken(")");
} else if (_value == ")") {
return null;
}
return new GroupingToken(_value);
}
public GroupingToken? closing_value { get => _closing_value(); }
}
class AtomToken : Token<string> {
private AtomToken(string value) : base(value) {}
private static IToken<string>? take(CharStream program) {
string value = "";
while (program.Available() > 0) {
char t = program.Get();
if (" \n()\"".Contains(t)) {
if (value.Equals("")) {
return null;
}
program.Rewind(1);
return new AtomToken(value);
}
value += t;
}
return null;
}
}
class CharStream: Stream<char> {
public CharStream(IList<char> items) : base(items) {}
public CharStream(string items) : base(items.ToCharArray().Cast<char>().ToList()) {}
}
public class StringTokenStream : Stream<Token<string>> {
private static readonly IList<Type> _classes = new List<Type> {
typeof(SpaceToken),
typeof(GroupingToken),
typeof(AtomToken),
};
protected StringTokenStream(IList<Token<string>> tokens) : base(tokens) {}
private static StringTokenStream generate(CharStream program) {
IList<Token<string>> result = new List<Token<string>>();
int prev_avail = 0;
while (true) {
if (prev_avail == program.Available() && prev_avail == 0) {
break;
} else if (prev_avail == program.Available()) {
throw new ApplicationException("Program is invalid");
}
prev_avail = program.Available();
foreach (Type c in _classes) {
Token<string>? t = (Token<string>?) c.GetMethod(
"take",
BindingFlags.NonPublic | BindingFlags.Static,
null,
CallingConventions.Any,
new Type[] { typeof(CharStream) },
null
)?.Invoke(
null,
new object[]{program}
);
if (t == null) {
program.Rewind();
continue;
}
program.Commit();
result.Add(t);
break;
}
}
return new StringTokenStream(result);
}
public static StringTokenStream generate(string program) {
return StringTokenStream.generate(new CharStream(program));
}
}
}

View file

@ -1,337 +0,0 @@
namespace Jellyfin.Plugin.SmartPlaylist.Lisp {
interface IAddable<T> where T : IAddable<T> {
static abstract T operator +(T left, T right);
}
interface ISubtractable<T> where T : ISubtractable<T> {
static abstract T operator -(T left, T right);
}
interface IMultiplicatable<T> where T : IMultiplicatable<T> {
static abstract T operator *(T left, T right);
}
interface IDivisible<T> where T : IDivisible<T> {
static abstract T operator /(T left, T right);
static abstract T operator %(T left, T right);
}
interface ISortable<T, E> where T : ISortable<T, E> {
static abstract E operator >(T left, T right);
static abstract E operator <(T left, T right);
static abstract E operator >=(T left, T right);
static abstract E operator <=(T left, T right);
}
interface IComparable<T, E> where T : IComparable<T, E> {
static abstract E operator ==(T left, T right);
static abstract E operator !=(T left, T right);
E Equals(T other);
}
interface IInner {
public object Inner();
}
public abstract class Expression: IComparable<Expression, bool> {
public override abstract string? ToString();
public abstract override int GetHashCode();
public abstract bool Equals(Expression other);
public override bool Equals(object? other) {
if (other is Expression other_e) {
return Equals(other_e);
}
return false;
}
public static bool operator ==(Expression left, Expression right) {
return left.Equals(right);
}
public static bool operator !=(Expression left, Expression right) {
return !left.Equals(right);
}
}
public abstract class Atom : Expression {}
public class Scalar<V> : Atom, IInner where V : notnull {
protected V _value;
public Scalar(V value) {
_value = value;
}
public override int GetHashCode() {
return 17 * 23 + _value.GetHashCode();
}
public override bool Equals(Expression other) {
if (other is Scalar<V> other_scalar) {
return _value.Equals(other_scalar._value);
}
return false;
}
public override string? ToString() {
return _value.ToString();
}
public V Value() {
return _value;
}
public object Inner() {
return _value;
}
}
public class Symbol : Atom {
private string _name;
public Symbol(string name) {
_name = name;
}
public override int GetHashCode() {
return 17 * 23 + _name.GetHashCode();
}
public override bool Equals(Expression other) {
if (other is Symbol other_symbol) {
return _name.Equals(other_symbol._name);
}
return false;
}
public override string? ToString() {
return _name.ToString();
}
public string Name() {
return _name;
}
}
public class Integer : Scalar<int>, IAddable<Integer>, ISubtractable<Integer>, IMultiplicatable<Integer>, IDivisible<Integer>, ISortable<Integer, Boolean> {
public Integer(int value) : base(value) {}
public static Integer operator +(Integer a, Integer b) {
return new Integer(a._value + b._value);
}
public static Integer operator -(Integer a, Integer b) {
return new Integer(a._value - b._value);
}
public static Integer operator *(Integer a, Integer b) {
return new Integer(a._value * b._value);
}
public static Integer operator /(Integer a, Integer b) {
return new Integer(a._value / b._value);
}
public static Integer operator %(Integer a, Integer b) {
return new Integer(a._value % b._value);
}
public static Boolean operator >(Integer a, Integer b) {
return (a._value > b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator <(Integer a, Integer b) {
return (a._value < b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator >=(Integer a, Integer b) {
return (a._value >= b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator <=(Integer a, Integer b) {
return (a._value <= b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public override int GetHashCode() {
return base.GetHashCode();
}
public override bool Equals(object? other) {
return base.Equals(other);
}
public static Boolean operator ==(Integer a, Integer b) {
return (a._value == b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator !=(Integer a, Integer b) {
return (a._value != b._value) ? Boolean.TRUE : Boolean.FALSE;
}
}
public class Boolean: Scalar<bool> {
public static Boolean TRUE = new Boolean(true);
public static Boolean FALSE = new Boolean(false);
private Boolean(bool value) : base(value) {}
public override string? ToString() {
if (_value) {
return "t";
}
return "nil";
}
public IList<Expression> ToList() {
if (_value) {
throw new ApplicationException("Cannot use t as list");
}
return new List<Expression>();
}
}
public class String: Scalar<string>, ISortable<String, Boolean> {
public String(string value) : base(value) {}
public override string? ToString() {
return $"\"{base.ToString()}\"";
}
public static Boolean operator <(String a, String b) {
return (a.Value().CompareTo(b.Value()) < 0) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator >(String a, String b) {
return b < a;
}
public static Boolean operator <=(String a, String b) {
return (a.Value().CompareTo(b.Value()) <= 0) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator >=(String a, String b) {
return b <= a;
}
public override int GetHashCode() {
return base.GetHashCode();
}
public override bool Equals(object? other) {
return base.Equals(other);
}
public static Boolean operator ==(String a, String b) {
return (a._value == b._value) ? Boolean.TRUE : Boolean.FALSE;
}
public static Boolean operator !=(String a, String b) {
return (a._value != b._value) ? Boolean.TRUE : Boolean.FALSE;
}
}
public class Cons: Expression {
public Expression Item1;
public Expression Item2;
public Cons(Expression item1, Expression item2) {
Item1 = item1;
Item2 = item2;
}
public static Expression FromList(IEnumerable<Expression> expressions) {
var e = expressions.ToList();
if (e.Count == 0) {
return Boolean.FALSE;
}
var item1 = expressions.First();
if (e.Count == 1) {
return new Cons(item1, Boolean.FALSE);
}
var item2 = expressions.Skip(1).ToList();
return new Cons(item1, FromList(item2));
}
public IEnumerable<Expression> ToList() {
var l = new List<Expression>();
l.Add(Item1);
if (Item2 == Boolean.FALSE) {
return l;
}
if (Item2 is Cons item2_cons) {
l.AddRange(item2_cons.ToList());
return l;
}
l.Add(Item2);
return l;
}
public override int GetHashCode() {
var hash = 17;
hash *= 23;
hash += Item1.GetHashCode();
hash *= 23;
hash += Item2.GetHashCode();
return hash;
}
public override bool Equals(Expression other) {
if (other is Cons other_list) {
return Item1.Equals(other_list.Item1) && Item2.Equals(other_list.Item2);
}
return false;
}
private string? ToStringSimple() {
if (Item2.Equals(Boolean.FALSE)) {
return Item1.ToString();
}
if (Item2 is Cons item2_cons) {
return $"{Item1} {item2_cons.ToStringSimple()}";
}
return $"{Item1} . {Item2}";
}
public override string? ToString() {
return $"({ToStringSimple()})";
}
}
public class Object : Scalar<object> {
internal Object(object value) : base(value) {}
public static Expression FromBase(object? o) {
if (o == null) {
return Boolean.FALSE;
}
switch (o) {
case bool b:
return b ? Boolean.TRUE : Boolean.FALSE;
case int i:
return new Integer(i);
case string s:
return new String(s);
case Expression e:
return e;
case IEnumerable<object> e:
return Cons.FromList(e.Select(x => FromBase(x)));
default:
return new Object(o);
}
}
}
public class Procedure : Expression {
private IEnumerable<Symbol> _parameters;
private Expression _body;
private bool _eval_args;
public Procedure(IEnumerable<Symbol> parameters, Expression body, bool eval_args) {
_parameters = parameters;
_body = body;
_eval_args = eval_args;
}
public override int GetHashCode() {
int hash = 17;
hash *= 23;
hash += _parameters.GetHashCode();
hash *= 23;
hash += _body.GetHashCode();
return hash;
}
public override bool Equals(Expression? other) {
if (other is Procedure other_p) {
return _parameters == other_p._parameters && _body == other_p._body;
}
return false;
}
public override string ToString() {
var star = _eval_args ? "" : "*";
return $"(lambda{star} {Cons.FromList(_parameters)} {_body})";
}
private Expression __eval(Executor e, Expression exp) {
if (!_eval_args) return exp;
return e.eval(exp);
}
private Expression _eval(Executor e, Expression exp) {
var r = __eval(e, exp);
//Console.WriteLine($"{exp} = {r}");
return r;
}
public Expression Call(Executor e, IList<Expression> args) {
Executor new_e = new Executor(new SubEnvironment(e.environment), e.builtins, e.builtinsLater);
var _params = _parameters.Select(x => x.Name()).ToArray();
var idx_rest = -1;
IList<(string, Expression)> name_args = new List<(string, Expression)>();
for (var i = 0; i < _parameters.Count(); i++) {
var name = _params[i];
if (name.Equals(".")) {
idx_rest = i + 1;
break;
}
name_args.Add((name, _eval(e, args[i])));
}
if (idx_rest > 0) {
name_args.Add((_params[idx_rest], Cons.FromList(args.Skip(idx_rest - 1).Select(x => _eval(e, x)))));
}
foreach (var na in name_args) {
new_e.environment.Set(na.Item1, na.Item2);
}
var r = new_e.eval(_body);
return r;
}
}
}

View file

@ -1,460 +0,0 @@
using System.Reflection;
using Jellyfin.Plugin.SmartPlaylist.Lisp.Compiler;
namespace Jellyfin.Plugin.SmartPlaylist.Lisp {
using Function = Func<IEnumerable<Expression>, Expression>;
using FunctionLater = Func<Executor, IEnumerable<Expression>, Expression>;
public interface IEnvironment<K, V> {
public V? Get(K k);
public void Set(K k, V v);
public IEnvironment<K, V>? Find(K k);
public IEnvironment<K, V> Parent(bool recursive);
}
public class Environment : Dictionary<string, Expression>, IEnvironment<string, Expression> {
public Expression? Get(string k) {
if (TryGetValue(k, out Expression? v)) {
return v;
}
return null;
}
public void Set(string k, Expression v) {
this[k] = v;
}
public IEnvironment<string, Expression>? Find(string k) {
if (ContainsKey(k)) {
return this;
}
return null;
}
public IEnvironment<string, Expression> Parent(bool recursive) {
return this;
}
}
public class DefaultEnvironment: Environment {
public DefaultEnvironment() {
var e = new Executor();
this["null"] = new Symbol("not");
this["list"] = e.eval("(lambda (. args) args)");
this["find"] = e.eval("(lambda (item list_) (if (null list_) nil (if (= item (car list_)) (car list_) (find item (cdr list_)))))");
this["map"] = e.eval("(lambda (fc l) (if (null l) nil (cons (fc (car l)) (map fc (cdr l)))))");
this["fold"] = e.eval("(lambda (fc i l) (if (null l) i (fold fc (fc i (car l)) (cdr l))))");
this["any"] = e.eval("(lambda (fc l) (apply or (map fc l)))");
this["all"] = e.eval("(lambda (fc l) (apply and (map fc l)))");
this["append"] = e.eval("(lambda (l i) (if (null l) i (cons (car l) (append (cdr l) i))))");
this["qsort"] = e.eval(
"""
(lambda
(fc list00)
(let
(getpivot
(lambda
(list0)
(car list0)))
(split
(lambda
(list0 pivot fc h0 h1)
(cond
((null list0) (list list0 pivot fc h0 h1))
((fc (car list0) pivot) (split (cdr list0) pivot fc h0 (cons (car list0) h1)))
(t (split (cdr list0) pivot fc (cons (car list0) h0) h1)))))
(sort
(lambda
(fc list0)
(cond
((null list0) nil)
((null (cdr list0)) list0)
(t
(let*
(halves (split list0 (getpivot list0) fc nil nil))
(h0 (car (cdr (cdr (cdr halves)))))
(h1 (car (cdr (cdr (cdr (cdr halves))))))
(append (sort fc h0) (sort fc h1)))))))
(sort fc list00)))
"""
);
}
}
public class SubEnvironment : Dictionary<string, Expression>, IEnvironment<string, Expression> {
private IEnvironment<string, Expression> _super;
public SubEnvironment(IEnvironment<string, Expression> super) {
_super = super;
}
public Expression? Get(string k) {
if (TryGetValue(k, out Expression? v)) {
return v;
}
return null;
}
public void Set(string k, Expression v) {
Add(k, v);
}
public IEnvironment<string, Expression>? Find(string k) {
if (ContainsKey(k)) {
return this;
}
return _super.Find(k);
}
public IEnvironment<string, Expression> Parent(bool recursive) {
if (recursive) {
return this._super.Parent(recursive);
}
return this._super;
}
}
public class Builtins : Dictionary<string, Function> {
public Builtins() : base() {
this["atom"] = _atom;
this["eq"] = _eq;
this["car"] = _car;
this["cdr"] = _cdr;
this["cons"] = _cons;
this["begin"] = _begin;
this["+"] = (x) => _agg((Integer a, Integer b) => a + b, x);
this["-"] = (x) => _agg((Integer a, Integer b) => a - b, x);
this["*"] = (x) => _agg((Integer a, Integer b) => a * b, x);
this["/"] = (x) => _agg((Integer a, Integer b) => a / b, x);
this["%"] = (x) => _agg((Integer a, Integer b) => a % b, x);
this["="] = (x) => _cmp((Atom a, Atom b) => (a == b)? Boolean.TRUE : Boolean.FALSE, x);
this["!="] = (x) => _cmp((Atom a, Atom b) => (a != b)? Boolean.TRUE : Boolean.FALSE, x);
this["<"] = (x) => _cmp((Integer a, Integer b) => a < b, x);
this["<="] = (x) => _cmp((Integer a, Integer b) => a <= b, x);
this[">"] = (x) => _cmp((Integer a, Integer b) => a > b, x);
this[">="] = (x) => _cmp((Integer a, Integer b) => a >= b, x);
this["not"] = (x) => {
return (x.First() == Boolean.FALSE) ? Boolean.TRUE : Boolean.FALSE;
};
this["string="] = (x) => _cmp((String a, String b) => a == b, x);
this["string!="] = (x) => _cmp((String a, String b) => a != b, x);
this["string>"] = (x) => _cmp((String a, String b) => a > b, x);
this["string>="] = (x) => _cmp((String a, String b) => a >= b, x);
this["string<"] = (x) => _cmp((String a, String b) => a < b, x);
this["string<="] = (x) => _cmp((String a, String b) => a <= b, x);
this["haskeys"] = _haskeys;
this["getitems"] = _getitems;
this["invoke"] = _invoke;
}
private static T _agg<T>(Func<T, T, T> op, IEnumerable<Expression> args) where T : Expression {
T agg = (T) args.First();
foreach (var arg in args.Skip(1)) {
var arg_ = (T) arg;
agg = op(agg, arg_);
}
return agg;
}
private static E _cmp<T, E>(Func<T, T, E> op, IEnumerable<Expression> args) where T : Expression where E : Expression {
return op((T) args.First(), (T) args.Skip(1).First());
}
private static Expression _atom(IEnumerable<Expression> args) {
return (args.First() is Atom) ? Boolean.TRUE : Boolean.FALSE;
}
private static Expression _eq(IEnumerable<Expression> args) {
return args.First().Equals(args.Skip(1).First()) ? Boolean.TRUE : Boolean.FALSE;
}
private static Expression _car(IEnumerable<Expression> args) {
return ((Cons)args.First()).Item1;
}
private static Expression _cdr(IEnumerable<Expression> args) {
return ((Cons)args.First()).Item2;
}
private static Expression _cons(IEnumerable<Expression> args) {
return new Cons(args.First(), args.Skip(1).First());
}
private static Expression _begin(IEnumerable<Expression> args) {
return args.Last();
}
private static Expression _haskeys(IEnumerable<Expression> args) {
Object o = new Object(((IInner) args.First()).Inner());
foreach (var e in args.Skip(1)) {
String s = (String) e;
PropertyInfo? pi = o.Value().GetType().GetProperty(s.Value());
if (pi != null) {
continue;
}
MethodInfo? mi = o.Value().GetType().GetMethod(s.Value());
if (mi != null) {
continue;
}
FieldInfo? fi = o.Value().GetType().GetField(s.Value());
if (fi != null) {
continue;
}
return Boolean.FALSE;
}
return Boolean.TRUE;
}
private static Expression _getitems(IEnumerable<Expression> args) {
Object o = new Object(((IInner) args.First()).Inner());
IList<Expression> r = new List<Expression>();
foreach (var e in args.Skip(1)) {
String s = (String) e;
PropertyInfo? pi = o.Value().GetType().GetProperty(s.Value());
if (pi != null) {
r.Add(Object.FromBase(pi.GetValue(o.Value())));
continue;
}
FieldInfo? fi = o.Value().GetType().GetField(s.Value());
if (fi != null) {
r.Add(Object.FromBase(fi.GetValue(o.Value())));
continue;
}
throw new ApplicationException($"{o.Value()} has no property or field {s.Value()}");
}
return Cons.FromList(r);
}
private static Expression _invoke(IEnumerable<Expression> args) {
Object o = new Object(((IInner) args.First()).Inner());
String s = (String) args.Skip(1).First();
IEnumerable<Expression> l;
if (args.Skip(2).First() is Boolean lb && lb == Boolean.FALSE) {
l = new List<Expression>();
} else if (args.Skip(2).First() is Cons lc) {
l = lc.ToList();
} else {
throw new ApplicationException($"Expected a list of arguments, got {args.Skip(2).First()}");
}
object[]? l_ = l.Select<Expression, object>(x => {
switch (x) {
case Integer s:
return s.Value();
case Boolean b:
return b.Value();
case String s:
return s.Value();
case Object o:
return o.Value();
case Cons c:
return c.ToList().ToList();
}
throw new ApplicationException($"Unhandled value {x} (type {x.GetType()})");
}).ToArray();
Type[] l_types = l_.Select( x => {
return x.GetType();
}).ToArray();
IList<Expression> r = new List<Expression>();
MethodInfo? mi = o.Value().GetType().GetMethod(s.Value(), l_types);
if (mi == null) {
throw new ApplicationException($"{o.Value()} has not method {s.Value()}");
}
return Object.FromBase(mi.Invoke(o.Value(), l_));
}
}
public class BuiltinsLater : Dictionary<string, FunctionLater> {
public BuiltinsLater() : base() {
this["quote"] = _quote;
this["eval"] = _eval;
this["cond"] = _cond;
this["if"] = _if;
this["define"] = _define;
this["let"] = _let;
this["let*"] = _let_star;
this["lambda"] = _lambda;
this["lambda*"] = _lambda_star;
this["apply"] = _apply;
this["and"] = (e, x) => {
Expression? r = null;
foreach (var xi in x) {
r = e.eval(xi);
if (r == Boolean.FALSE) {
return r;
}
}
if (r is null) {
return Boolean.FALSE;
}
return r;
};
this["or"] = (e, x) => {
foreach (var xi in x) {
var r = e.eval(xi);
if (r != Boolean.FALSE) {
return r;
}
}
return Boolean.FALSE;
};
}
private static Expression _quote(Executor e, IEnumerable<Expression> args) {
return args.First();
}
private static Expression _eval(Executor e, IEnumerable<Expression> args) {
return e.eval(e.eval(args.First()));
}
private static Expression _cond(Executor e, IEnumerable<Expression> args) {
foreach (var a in args) {
if (a is Cons a_cons) {
var a_ = a_cons.ToList();
if (!e.eval(a_.First()).Equals(Boolean.FALSE)) {
return e.eval(a_.Skip(1).First());
}
} else {
throw new ApplicationException($"Incorrect arguments to cond, expected list: {args}");
}
}
return Boolean.FALSE;
}
private static Expression _if(Executor e, IEnumerable<Expression> args) {
if (e.eval(args.First()).Equals(Boolean.FALSE)) {
return e.eval(args.Skip(2).First());
}
return e.eval(args.Skip(1).First());
}
private static Expression _define(Executor e, IEnumerable<Expression> args) {
Symbol refname = (Symbol) args.First();
e.environment.Parent(true).Set(refname.Name(), args.Skip(1).Select(x => e.eval(x)).First());
return Boolean.TRUE;
}
private static Expression _let_star(Executor e, IEnumerable<Expression> args) {
Executor new_e = new Executor(new SubEnvironment(e.environment), e.builtins, e.builtinsLater);
foreach (var pair in args.SkipLast(1)) {
if (pair is not Cons pair_cons) {
throw new ApplicationException("No expression for let*");
}
Symbol refname = (Symbol) pair_cons.Item1;
Expression exp = ((Cons) pair_cons.Item2).Item1;
new_e.environment.Set(refname.Name(), new_e.eval(exp));
}
return new_e.eval(args.Last());
}
private static Expression _let(Executor e, IEnumerable<Expression> args) {
Executor new_e = new Executor(new SubEnvironment(e.environment), e.builtins, e.builtinsLater);
List<(Symbol, Expression)> vars = new List<(Symbol, Expression)>();
foreach (var pair in args.SkipLast(1)) {
if (pair is not Cons pair_cons) {
throw new ApplicationException("");
}
Symbol refname = (Symbol) pair_cons.Item1;
Expression exp_ = ((Cons) pair_cons.Item2).Item1;
vars.Add((refname, e.eval(exp_)));
}
foreach (var pair in vars) {
new_e.environment.Set(pair.Item1.Name(), pair.Item2);
}
return new_e.eval(args.Last());
}
private static Expression _lambda(Executor e, IEnumerable<Expression> args) {
IEnumerable<Symbol> proc_args;
if (args.First() is Cons proc_args_) { proc_args = proc_args_.ToList().Select(x => (Symbol) x); }
else if (args.First() == Boolean.FALSE) { proc_args = new List<Symbol>(); }
else {
throw new ApplicationException("");
}
return new Procedure(proc_args, args.Skip(1).First(), true);
}
private static Expression _lambda_star(Executor e, IEnumerable<Expression> args) {
IEnumerable<Symbol> proc_args;
if (args.First() is Cons proc_args_) { proc_args = proc_args_.ToList().Select(x => (Symbol) x); }
else if (args.First() == Boolean.FALSE) { proc_args = new List<Symbol>(); }
else {
throw new ApplicationException("");
}
return new Procedure(proc_args, args.Skip(1).First(), false);
}
private static Expression _apply(Executor e, IEnumerable<Expression> args) {
return e.eval(new Cons(args.First(), e.eval(args.Skip(1).First())));
}
}
public class Executor {
IEnvironment<string, Expression> _environment;
Builtins _builtins;
BuiltinsLater _builtinsLater;
public Executor(IEnvironment<string, Expression> environment, Builtins builtins, BuiltinsLater builtinsLater) {
_environment = environment;
_builtins = builtins;
_builtinsLater = builtinsLater;
}
public Executor(IEnvironment<string, Expression> environment) {
_environment = environment;
_builtins = new Builtins();
_builtinsLater = new BuiltinsLater();
}
public Executor() {
_environment = new Environment();
_builtins = new Builtins();
_builtinsLater = new BuiltinsLater();
}
public IEnvironment<string, Expression> environment { get => _environment; }
public Builtins builtins { get => _builtins; }
public BuiltinsLater builtinsLater { get => _builtinsLater; }
public Expression? EvalFunction(Symbol fcname, IEnumerable<Expression> args) {
if (builtins.ContainsKey(fcname.Name())) {
return builtins[fcname.Name()](args.Select(x => eval(x)).ToList()); // call ToList for sideeffect
}
if (builtinsLater.ContainsKey(fcname.Name())) {
return builtinsLater[fcname.Name()](this, args);
}
return null;
}
public Expression eval(Expression expression) {
switch (expression) {
case Symbol s:
if (_environment.Find(s.Name()) is not IEnvironment<string, Expression> env) {
throw new ApplicationException($"Could not find '{s.Name()}'");
}
var r_ = env.Get(s.Name());
if (r_ is null) {
throw new ApplicationException($"Could not find '{s.Name()}'");
}
return r_;
case Boolean b:
return b;
case Integer i:
return i;
case String s:
return s;
case Object o:
return o;
case Procedure p:
return p;
case Cons cons:
var l = cons.ToList();
if (cons.Item1 is Symbol cons_item1_symbol) {
Expression? r = EvalFunction(cons_item1_symbol, l.Skip(1));
if (r is not null) { return r; }
}
var eval_Item1 = eval(cons.Item1);
if (eval_Item1 is Symbol eval_item1_symbol1) {
Expression? r = EvalFunction(eval_item1_symbol1, l.Skip(1));
if (r is not null) { return r; }
}
if (eval_Item1 is Procedure eval_item1_procedure) {
return eval_item1_procedure.Call(this, l.Skip(1).Select(x => x).ToList());
}
throw new ApplicationException($"Not handled case (type = {eval_Item1.GetType()}) '{cons}'");
}
throw new ApplicationException($"Not handled case '{expression}'");
}
public Expression eval(Parser p) {
return eval(p.parse());
}
public Expression eval(StringTokenStream sts) {
return eval(new Parser(sts));
}
public Expression eval(string p) {
return eval(StringTokenStream.generate(p));
}
}
}

View file

@ -1,27 +0,0 @@
using System.Globalization;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization;
namespace Jellyfin.Plugin.SmartPlaylist {
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages {
public Plugin(
IApplicationPaths applicationPaths,
IXmlSerializer xmlSerializer
) : base (applicationPaths, xmlSerializer) {
Instance = this;
}
public static Plugin? Instance {get; private set; }
public override string Name => "Smart Playlist";
public override Guid Id => Guid.Parse("dd2326e3-4d3e-4bfc-80e6-28502c1131df");
public IEnumerable<PluginPageInfo> GetPages() {
return new[] {
new PluginPageInfo {
Name = this.Name,
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.configPage.html", GetType().Namespace)
}
};
}
}
}

View file

@ -1,45 +0,0 @@
using MediaBrowser.Model.Plugins;
namespace Jellyfin.Plugin.SmartPlaylist {
public class PluginConfiguration : BasePluginConfiguration {
public PluginConfiguration() {
InitialProgram = """
(begin
(define lower
(lambda (s)
(invoke s "ToLower" nil)))
(define is-genre
(lambda (g g-list)
(any
(lambda (x)
(invoke (lower x) "Contains" (list (lower g))))
g-list)))
(define is-genre-exact
(lambda (g g-list)
(find g g-list)))
(define genre-list
(lambda nil
(let
(_g (getitems item "Genres"))
(if (null _g)
nil
(car _g)))))
(define is-favorite
(lambda nil
(invoke item "IsFavoriteOrLiked" (list user))))
(define is-type
(lambda (x)
(and
(haskeys item "GetClientTypeName")
(invoke (invoke item "GetClientTypeName" nil) "Equals" (list x)))))
(define name-contains
(lambda (x)
(invoke (lower (car (getitems item "Name"))) "Contains" (list (lower x)))))
(define is-favourite is-favorite)
(define all-genres (lambda (want have) (all (lambda (x) (is-genre x have)) want)))
(define any-genres (lambda (want have) (any (lambda (x) (is-genre x have)) want))))
""";
}
public string InitialProgram { get; set; }
}
}

View file

@ -1,196 +0,0 @@
using System.Globalization;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Playlists;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.IO;
using Jellyfin.Data.Entities;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Playlists;
using Jellyfin.Plugin.SmartPlaylist.Lisp;
using Jellyfin.Plugin.SmartPlaylist.Lisp.Compiler;
using Lisp_Object = Jellyfin.Plugin.SmartPlaylist.Lisp.Object;
using Lisp_Boolean = Jellyfin.Plugin.SmartPlaylist.Lisp.Boolean;
namespace Jellyfin.Plugin.SmartPlaylist.ScheduledTasks {
public class GeneratePlaylist : IScheduledTask {
public static readonly BaseItemKind[] AvailableFilterItems = {
BaseItemKind.Audio,
BaseItemKind.MusicAlbum,
BaseItemKind.Playlist,
};
private readonly ILogger _logger;
private readonly ILibraryManager _libraryManager;
private readonly IUserManager _userManager;
private readonly IProviderManager _providerManager;
private readonly IFileSystem _fileSystem;
private readonly IPlaylistManager _playlistManager;
private readonly IStore _store;
public GeneratePlaylist(
ILogger<Plugin> logger,
ILibraryManager libraryManager,
IUserManager userManager,
IProviderManager providerManager,
IFileSystem fileSystem,
IPlaylistManager playlistManager,
IServerApplicationPaths serverApplicationPaths
) {
_logger = logger;
_libraryManager = libraryManager;
_userManager = userManager;
_providerManager = providerManager;
_fileSystem = fileSystem;
_playlistManager = playlistManager;
_store = new Store(new SmartPlaylistFileSystem(serverApplicationPaths));
}
public string Category => "Library";
public string Name => "(re)generate Smart Playlists";
public string Description => "Generate or regenerate all Smart Playlists";
public string Key => nameof(GeneratePlaylist);
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers() {
return new[] {
new TaskTriggerInfo {
IntervalTicks = TimeSpan.FromHours(24).Ticks,
Type = TaskTriggerInfo.TriggerInterval,
}
};
}
private void GetUsers() {
foreach (var user in _userManager.Users) {
_logger.LogInformation("User {0}", user);
var query = new InternalItemsQuery(user) {
IncludeItemTypes = AvailableFilterItems,
Recursive = true,
};
foreach (BaseItem item in _libraryManager.GetItemsResult(query).Items) {
_logger.LogInformation("Item {0}", item);
}
}
}
private PlaylistId CreateNewPlaylist(string name, UserId userId) {
_logger.LogDebug("Creating playlist '{0}'", name);
var req = new PlaylistCreationRequest {
Name = name,
UserId = userId,
Users = [new PlaylistUserPermissions(userId)],
Public = false,
};
var playlistGuid = Guid.Parse(_playlistManager.CreatePlaylist(req).Result.Id);
return playlistGuid;
}
private IEnumerable<Guid> FilterPlaylistItems(IEnumerable<BaseItem> items, User user, SmartPlaylistDto smartPlaylist) {
List<BaseItem> results = new List<BaseItem>();
Expression expression = new Parser(StringTokenStream.generate(smartPlaylist.Program)).parse(); // parse here, so that we don't repeat the work for each item
Executor executor = new Executor(new DefaultEnvironment());
executor.environment.Set("user", Lisp_Object.FromBase(user));
if (Plugin.Instance is not null) {
executor.eval(Plugin.Instance.Configuration.InitialProgram);
} else {
throw new ApplicationException("Plugin Instance is not yet initialized");
}
foreach (var i in items) {
executor.environment.Set("item", Lisp_Object.FromBase(i));
var r = executor.eval(expression);
_logger.LogTrace("Item {0} evaluated to {1}", i, r.ToString());
if ((r is not Lisp_Boolean r_bool) || (r_bool.Value())) {
_logger.LogDebug("Added '{0}' to Smart Playlist {1}", i, smartPlaylist.Name);
results.Add(i);
}
}
executor = new Executor(new DefaultEnvironment());
executor.environment.Set("user", Lisp_Object.FromBase(user));
executor.environment.Set("items", Lisp_Object.FromBase(results));
results = new List<BaseItem>();
var sort_result = executor.eval(smartPlaylist.SortProgram);
if (sort_result is Cons sorted_items) {
foreach (var i in sorted_items.ToList()) {
if (i is Lisp_Object iObject && iObject.Value() is BaseItem iBaseItem) {
results.Add(iBaseItem);
continue;
}
throw new ApplicationException($"Returned sorted list does contain unexpected items, got {i}");
}
} else if (sort_result == Lisp_Boolean.FALSE) {
} else {
throw new ApplicationException($"Did not return a list of items, returned {sort_result}");
}
return results.Select(x => x.Id);
}
private IEnumerable<BaseItem> GetAllUserMedia(User user) {
var req = new InternalItemsQuery(user) {
IncludeItemTypes = AvailableFilterItems,
Recursive = true,
};
return _libraryManager.GetItemsResult(req).Items;
}
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken) {
_logger.LogInformation("Started regenerate Smart Playlists");
foreach (SmartPlaylistDto dto in await _store.GetAllSmartPlaylistsAsync()) {
var changedDto = false;
if (dto.Playlists.Length == 0) {
dto.Playlists = _userManager.UsersIds.Select(x => new SmartPlaylistLinkDto {
UserId = x,
PlaylistId = CreateNewPlaylist(dto.Name, x),
}).ToArray();
changedDto = true;
}
foreach (SmartPlaylistLinkDto playlistLink in dto.Playlists) {
if (playlistLink.PlaylistId == Guid.Empty) {
// not initialized
playlistLink.PlaylistId = CreateNewPlaylist(dto.Name, playlistLink.UserId);
changedDto = true;
} else if (_playlistManager.GetPlaylists(playlistLink.UserId).Where(x => x.Id == playlistLink.PlaylistId).ToArray().Length == 0) {
// somehow the corresponding playlist doesnt
// exist anymore, did the user delete it?
playlistLink.PlaylistId = CreateNewPlaylist(dto.Name, playlistLink.UserId);
changedDto = true;
}
}
if (changedDto) {
_store.DeleteSmartPlaylist(dto); // delete in case the file was not the canonical one.
await _store.SaveSmartPlaylistAsync(dto);
}
var i = 0;
foreach (SmartPlaylistLinkDto playlistLink in dto.Playlists) {
User? user = _userManager.GetUserById(playlistLink.UserId);
if (user == null) {
continue;
}
var insertItems = FilterPlaylistItems(GetAllUserMedia(user), user, dto).ToArray();
var playlist = _playlistManager.GetPlaylists(playlistLink.UserId).Where(x => x.Id == playlistLink.PlaylistId).First();
await ClearPlaylist(playlist);
await _playlistManager.AddItemToPlaylistAsync(playlist.Id, insertItems, playlistLink.UserId);
i += 1;
progress.Report(100 * ((double)i)/dto.Playlists.Count());
}
}
}
private async Task ClearPlaylist(Playlist playlist) {
// fuck if I know
if (_libraryManager.GetItemById(playlist.Id) is not Playlist playlist_new) {
throw new ArgumentException("");
}
var existingItems = playlist_new.GetManageableItems().ToList();
await _playlistManager.RemoveItemFromPlaylistAsync(playlist.Id.ToString(), existingItems.Select(x => x.Item1.ItemId?.ToString("N", CultureInfo.InvariantCulture)));
}
}
}

View file

@ -1,111 +0,0 @@
using System.Runtime.Serialization;
namespace Jellyfin.Plugin.SmartPlaylist {
class GuidDeserializer {
public static Guid deserialize(string v) {
if (v.Length == 32) {
return Guid.ParseExact(v, "N");
}
return Guid.Parse(v);
}
}
[Serializable]
public class SmartPlaylistLinkDto : ISerializable {
public PlaylistId PlaylistId { get; set; }
public UserId UserId { get; set; }
public SmartPlaylistLinkDto() {
PlaylistId = Guid.Empty;
UserId = Guid.Empty;
}
protected SmartPlaylistLinkDto(SerializationInfo info, StreamingContext context) {
if (info.GetValue("PlaylistId", typeof(PlaylistId)) is PlaylistId _PlaylistId) {
PlaylistId = _PlaylistId;
} else {
PlaylistId = Guid.Empty;
}
if (info.GetValue("UserId", typeof(UserId)) is UserId _UserId) {
UserId = _UserId;
} else {
UserId = Guid.Empty;
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("PlaylistId", PlaylistId);
info.AddValue("UserId", UserId);
}
}
[Serializable]
public class SmartPlaylistDto : ISerializable {
private static string DEFAULT_PROGRAM = "(begin (invoke item \"IsFavoriteOrLiked\" (list user)))";
private static string DEFAULT_SORT_PROGRAM = "(begin items)";
public SmartPlaylistId Id { get; set; }
public SmartPlaylistLinkDto[] Playlists { get; set; }
public string Name { get; set; }
public string Program { get; set; }
public string SortProgram { get; set; }
public string? Filename { get; set; }
public bool Enabled { get; set; }
public SmartPlaylistDto() {
Id = "";
Playlists = [];
Name = Id.ToString();
Program = DEFAULT_PROGRAM;
SortProgram = DEFAULT_SORT_PROGRAM;
Filename = null;
Enabled = true;
}
protected SmartPlaylistDto(SerializationInfo info, StreamingContext context) {
if (info.GetValue("Id", typeof(SmartPlaylistId)) is SmartPlaylistId _Id) {
Id = _Id;
} else {
Id = "";
}
if (info.GetValue("Playlists", typeof(SmartPlaylistLinkDto[])) is SmartPlaylistLinkDto[] _Playlists) {
Playlists = _Playlists;
} else {
Playlists = [];
}
if (info.GetValue("Name", typeof(string)) is string _Name) {
Name = _Name;
} else {
Name = Id.ToString();
}
if (info.GetValue("Program", typeof(string)) is string _Program) {
Program = _Program;
} else {
Program = DEFAULT_PROGRAM;
}
if (info.GetValue("SortProgram", typeof(string)) is string _SortProgram) {
SortProgram = _SortProgram;
} else {
SortProgram = DEFAULT_SORT_PROGRAM;
}
if (info.GetValue("Filename", typeof(string)) is string _Filename) {
Filename = _Filename;
} else {
Filename = null;
}
if (info.GetValue("Enabled", typeof(bool)) is bool _Enabled) {
Enabled = _Enabled;
} else {
Enabled = true;
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Id", Id);
info.AddValue("Playlists", Playlists);
info.AddValue("Name", Name);
info.AddValue("Program", Program);
info.AddValue("Filename", Filename);
info.AddValue("Enabled", Enabled);
}
}
}

View file

@ -1,36 +0,0 @@
using MediaBrowser.Controller;
namespace Jellyfin.Plugin.SmartPlaylist {
public interface ISmartPlaylistFileSystem {
public string StoragePath { get; }
public string GetSmartPlaylistFilePath(SmartPlaylistId smartPlaylistId);
public string FindSmartPlaylistFilePath(SmartPlaylistId smartPlaylistId);
public string[] FindAllSmartPlaylistFilePaths();
}
public class SmartPlaylistFileSystem : ISmartPlaylistFileSystem {
public SmartPlaylistFileSystem(IServerApplicationPaths serverApplicationPaths) {
StoragePath = Path.Combine(serverApplicationPaths.DataPath, "smartplaylists");
if (!Directory.Exists(StoragePath)) { Directory.CreateDirectory(StoragePath); }
}
public string StoragePath { get; }
public string GetSmartPlaylistFilePath(SmartPlaylistId smartPlaylistId) {
return Path.Combine(StoragePath, $"{smartPlaylistId}.yaml");
}
public string FindSmartPlaylistFilePath(SmartPlaylistId smartPlaylistId) {
return Directory.GetFiles(StoragePath, $"{smartPlaylistId}.yaml", SearchOption.AllDirectories).Concat(
Directory.GetFiles(StoragePath, $"{smartPlaylistId}.yml", SearchOption.AllDirectories)
).Concat(
Directory.GetFiles(StoragePath, $"{smartPlaylistId}.json", SearchOption.AllDirectories)
).First();
}
public string[] FindAllSmartPlaylistFilePaths() {
return Directory.GetFiles(StoragePath, "*.yaml", SearchOption.AllDirectories).Concat(
Directory.GetFiles(StoragePath, "*.yml", SearchOption.AllDirectories)
).Concat(
Directory.GetFiles(StoragePath, "*.json", SearchOption.AllDirectories)
).ToArray();
}
}
}

View file

@ -1,62 +0,0 @@
using YamlDotNet.Serialization;
namespace Jellyfin.Plugin.SmartPlaylist {
public interface IStore {
Task<SmartPlaylistDto> GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId);
Task<SmartPlaylistDto[]> GetAllSmartPlaylistsAsync();
Task SaveSmartPlaylistAsync(SmartPlaylistDto smartPlaylist);
void DeleteSmartPlaylist(SmartPlaylistDto smartPlaylist);
}
public class Store : IStore {
private readonly ISmartPlaylistFileSystem _fileSystem;
public Store(ISmartPlaylistFileSystem fileSystem) {
_fileSystem = fileSystem;
}
private async Task<SmartPlaylistDto> LoadPlaylistAsync(string filename) {
var r = await File.ReadAllTextAsync(filename);
if (r.Equals("")) {
r = "{}";
}
var dto = new DeserializerBuilder().Build().Deserialize<SmartPlaylistDto>(r);
if (dto == null)
{
throw new ApplicationException("");
}
if (dto.Id != Path.GetFileNameWithoutExtension(filename)) {
dto.Id = Path.GetFileNameWithoutExtension(filename);
}
if (dto.Name != Path.GetFileNameWithoutExtension(filename)) {
dto.Name = Path.GetFileNameWithoutExtension(filename);
}
if (dto.Filename != filename) {
dto.Filename = filename;
}
return dto;
}
public async Task<SmartPlaylistDto> GetSmartPlaylistAsync(SmartPlaylistId smartPlaylistId) {
string filename = _fileSystem.FindSmartPlaylistFilePath(smartPlaylistId);
return await LoadPlaylistAsync(filename).ConfigureAwait(false);
}
public async Task<SmartPlaylistDto[]> GetAllSmartPlaylistsAsync() {
var t = _fileSystem.FindAllSmartPlaylistFilePaths().Select(LoadPlaylistAsync).ToArray();
await Task.WhenAll(t).ConfigureAwait(false);
return t.Where(x => x != null).Select(x => x.Result).ToArray();
}
public async Task SaveSmartPlaylistAsync(SmartPlaylistDto smartPlaylist) {
string filename = _fileSystem.GetSmartPlaylistFilePath(smartPlaylist.Id);
var text = new SerializerBuilder().Build().Serialize(smartPlaylist);
await File.WriteAllTextAsync(filename, text);
}
private void DeleteSmartPlaylistById(SmartPlaylistId smartPlaylistId) {
try {
string filename = _fileSystem.FindSmartPlaylistFilePath(smartPlaylistId);
if (File.Exists(filename)) { File.Delete(filename); }
} catch (System.InvalidOperationException) {}
}
public void DeleteSmartPlaylist(SmartPlaylistDto smartPlaylist) {
if (File.Exists(smartPlaylist.Filename)) { File.Delete(smartPlaylist.Filename); }
DeleteSmartPlaylistById(smartPlaylist.Id);
}
}
}

View file

@ -1,5 +0,0 @@
global using System;
global using UserId = System.Guid;
global using PlaylistId = System.Guid;
global using SmartPlaylistId = string;

View file

@ -1,61 +0,0 @@
namespace Jellyfin.Plugin.SmartPlaylist.Util {
public interface IStream<T> {
int Available();
T Get();
int Commit();
int Rewind();
int Rewind(int n);
int Consumed();
IStream<T> Copy();
}
public class Stream<T> : IStream<T> {
private readonly IList<T> _items;
private int _cursor;
private int _ephemeralCursor;
protected Stream(IList<T> items) {
_items = items;
_cursor = 0;
_ephemeralCursor = 0;
}
private Stream(IList<T> items, int cursor, int ephemeralCursor) {
_items = items;
_cursor = cursor;
_ephemeralCursor = ephemeralCursor;
}
public int Available() {
return _items.Count - _ephemeralCursor;
}
public T Get() {
return _items[_ephemeralCursor++];
}
public int Commit() {
int diff = Consumed();
_cursor = _ephemeralCursor;
return diff;
}
public int Rewind() {
int diff = Consumed();
_ephemeralCursor = _cursor;
return diff;
}
public int Rewind(int n) {
int diff = Consumed();
if (diff < n) {
n = diff;
}
_ephemeralCursor -= n;
return n;
}
public int Consumed() {
return _ephemeralCursor - _cursor;
}
public IStream<T> Copy() {
return new Stream<T>(_items, _cursor, _ephemeralCursor);
}
}
}

View file

@ -1,54 +0,0 @@
name: Smart Playlist
guid: dd2326e3-4d3e-4bfc-80e6-28502c1131df
version: 0.3.0.0
targetAbi: 10.10.3.0
framework: net8.0
owner: redxef
overview: Smart playlists with Lisp filter engine.
description: |
Create smart playlists with a Lisp filter engine.
The same playlist definition can be used for multiple users.
category: "General"
artifacts:
- jellyfin-smart-playlist.dll
- YamlDotNet.dll
changelog: |
## v0.3.0.0
- Add a second program (`SortProgram`) which is run after the filtering, this
program should return the list of items, but in the order in which they should appear in
the playlist. The default is `(begin items)` which returns the list as is.
- Extend builtin lisp definitions: add `qsort` and string comparison methods
- Extend default program definitions: add `all-genres` and `any-genres` to quickly specify a list of genres which to include (or excluding when negating)
- Update Jellyfin to v 10.10.3
**Fixes**:
- The progress report now correctly gives a percentage in the range [0, 100].
## v0.2.2.0
- Update Jellyfin to v 10.10.2
## v0.2.1.0
- Make default program configuration a textarea in the settings page
- Add convinience definitions: `is-type`, `name-contains`
- Update YamlDotNet to v 16.2.0
**Fixes**:
- The default program was malformed, a closing bracket was at the wrong position
- The `haskeys` function could only be called on Objects
## v0.2.0.0
- Switch to yaml loading, old json files are still accepted
- Rework lisp interpreter to be more conventional
- Use arbitrary strings as ids for playlists
- Add configuration page with some default definitions for
the filter expressions.
**Breaking Changes**:
- The lisp interpreter will now only detect strings in double quotes (`"`).
- The interpreter will also not allow specifying lists without quoting them.
`(1 2 3)` ... used to work but will no longer, replace by either specifying
the list as `(list 1 2 3)` or `(quote (1 2 3))`.
## v0.1.1.0
- Initial Alpha release.

View file

@ -1,60 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SmartPlaylist</title>
</head>
<body>
<div id="SmartPlaylistConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
<div data-role="content">
<div class="content-primary">
<form id="SmartPlaylistConfigForm">
<div class="inputContainer">
<label class="inputLabel inputLabelUnfocused" for="InitialProgram">Initial Program</label>
<div class="fieldDescription">A program which can set up the environment</div>
<textarea id="InitialProgram" class="emby-input smartplaylist-monospace" name="InitialProgram" rows="16" cols="120"></textarea>
</div>
<div>
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
<span>Save</span>
</button>
</div>
</form>
</div>
</div>
<style>
.smartplaylist-monospace {
font-family: monospace;
}
</style>
<script type="text/javascript">
var SmartPlaylistConfig = {
pluginUniqueId: 'dd2326e3-4d3e-4bfc-80e6-28502c1131df'
};
document.querySelector('#SmartPlaylistConfigPage')
.addEventListener('pageshow', function() {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(SmartPlaylistConfig.pluginUniqueId).then(function (config) {
document.querySelector('#InitialProgram').value = config.InitialProgram;
Dashboard.hideLoadingMsg();
});
});
document.querySelector('#SmartPlaylistConfigForm')
.addEventListener('submit', function(e) {
Dashboard.showLoadingMsg();
ApiClient.getPluginConfiguration(SmartPlaylistConfig.pluginUniqueId).then(function (config) {
config.InitialProgram = document.querySelector('#InitialProgram').value;
ApiClient.updatePluginConfiguration(SmartPlaylistConfig.pluginUniqueId, config).then(function (result) {
Dashboard.processPluginConfigurationUpdateResult(result);
});
});
e.preventDefault();
return false;
});
</script>
</div>
</body>
</html>

View file

@ -1,22 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Jellyfin.Plugin.SmartPlaylist</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>0.3.0.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Jellyfin.Controller" Version="10.10.3" />
<PackageReference Include="Jellyfin.Model" Version="10.10.3" />
<PackageReference Include="YamlDotNet" Version="16.2.0" />
</ItemGroup>
<ItemGroup>
<None Remove="configPage.html"/>
<EmbeddedResource Include="configPage.html"/>
</ItemGroup>
</Project>

235
LICENSE
View file

@ -1,235 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
jellyfin-smartplaylist-plugin
Copyright (C) 2024 redxef
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

164
README.md
View file

@ -1,164 +0,0 @@
# Jellyfin SmartPlaylist Plugin
Smart playlists with Lisp filter engine.
This readme contains instructions for the most recent changes in
the development branch (`main`). To view the file appropriate
for your version select the tag corresponding to your version.
The latest version is [v0.3.0.0](https://gitea.redxef.at/redxef/jellyfin-smart-playlist/src/tag/v0.3.0.0).
## How to use
After [installing](#installation) the plugin and restarting Jellyfin
create a empty file in `config/data/smartplaylists` like this, maybe
you want to generate a playlist of your favourite rock songs:
```
$ touch config/data/smartplaylists/Rock.yaml
```
Afterwards run the Task `(re)generate Smart Playlists`, this will rename
the `yaml` file and populate it with some default values. You can now
adjust the file to your liking. [Go here](examples.md) to see more
examples.
```yaml
Id: Rock
Playlists:
- PlaylistId: 24f12e1e-3278-d6d6-0ca4-066e93296c95
UserId: 6eec632a-ff0d-4d09-aad0-bf9e90b14bc6
Name: Rock
Program: (begin (invoke item "IsFavoriteOrLiked" (user)))
SortProgram: (begin items)
Filename: /config/data/smartplaylists/Rock.yaml
Enabled: true
```
This is the default configuration and will always match all your
favorite songs (and songs which are in favourited albums).
To change the filter you can append a `|` (pipe) to the Program
line and write multiline filters like this:
```yaml
Porgram: |
(begin
(invoke item "IsFavoriteOrLiked" (list user)))
```
This is equivalent to the above example (not counting the other
fields obviously).
### Id
Arbitrary Id assigned to this playlist, can usually be left alone.
### Playlists
A list of Playlist/User mappings. By default all users get an entry.
The ids must have the dashes in them as of now. To convert a id
from without dashes to the canonical form run this command:
`echo '<your id here>' | python3 -c 'import uuid; import sys; print(uuid.UUID(sys.stdin.read().strip()))'`
To get your user id navigate to your user profile and copy the part
after `userId` in the address bar.
#### PlaylistId
The id of the playlist that should be managed, must be owned by the
corresponding user.
#### UserId
The user associated with this playlist.
### Name
The name of the generated playlists, this is just a default value.
If the user changes the name of their playlist the plugin will
still work and remember the correct playlist.
### Program
A lisp program to decide on a per item basis if it should be included in
the playlist, return `nil` to not include items, return any other value
to include them. Global variables `user` and `item` are predefined
and contain a [User](https://github.com/jellyfin/jellyfin/blob/master/Jellyfin.Data/Entities/User.cs) and
[BaseItem](https://github.com/jellyfin/jellyfin/blob/master/MediaBrowser.Controller/Entities/BaseItem.cs)
respectively.
**!!! The filter expression will include all items matching, if you do
not specify the kind of item to include/exclude all of them will be
added. Should you allow a playlist to be included all of it's items
will be added to the generated playlist !!!**
It's best to be explicit and always specify the item kinds you want to
include: `(and (or (is-type "MusicAlbum") (is-type "Audio")) . rest of filter)`.
The configuration page defines some useful functions to make it easier
to create filters. The above filter for liked items could be simplified
to: `(is-favourite)`.
### SortProgram
This works exactly like [Program](#program), but the input is the
user and a list of items (`items`) matched by [Program](#program).
The default is `(begin items)`, which doesn't sort at all. To sort
the items by name you could use the following program:
```lisp
(qsort
(lambda
(a b)
(string>
(car (getitems a "Name"))
(car (getitems b "Name"))))
items)
```
#### Available definitions
- **lower**: lowercases a string (`(eq (lower "SomeString") "somestring")`)
- **is-genre**: check if the item is of this genre, partial matches
allowed, the example filter would match the genre "Nu-Metal" (`(is-genre "metal" (genre-list))`)
- **is-genre-exact**: the same as `is-genre`, but does not match paritally
- **is-favorite**: matches a favorite item (`(is-favorite)`)
- **is-type**: matches the type of item look at
[BaseItemKind.cs](https://github.com/jellyfin/jellyfin/blob/master/Jellyfin.Data/Enums/BaseItemKind.cs)
for a list of items. The plugin has enabled support for `Audio, MusicAlbum, Playlist` (`(is-type "Audio")`)
### Filename
The path to this file, only used internally and updated by the program.
### Enabled
Enable this playlist, currently ignored.
## Installation
Add the [plugin repository](https://jellyfin.org/docs/general/server/plugins/#catalog)
to Jellyfin:
`https://gitea.redxef.at/redxef/jellyfin-smart-playlist/raw/branch/manifest/manifest.json`
Go to `Dashboard>Catalog>(Gear)>(Plus)` and paste the provided link into
the field labeled `Repository URL`, give the plugin a descriptive name
too.
## Releasing a new version
1. Write the changelog: `git log --oneline $prev_version..`
2. Update the following files to include up-to-date version numbers
and changelogs, if applicable:
- `README.md`
- `Jellyfin.Plugin.SmartPlaylist/build.yaml`
- `Jellyfin.Plugin.SmartPlaylist/jellyfin-smart-playlist.csproj`
Don't forget to also bump the ABI version of Jellyfin.
3. Push the changes
4. Create a new release with the changelog, mark as pre-release if
applicable.
5. Done! The build pipeline will do the rest.

3
Test/.gitignore vendored
View file

@ -1,3 +0,0 @@
cache
config
media

View file

@ -1,21 +0,0 @@
#!/bin/sh
JELLYFIN=jellyfin/jellyfin
set -eu
cd "$(dirname "$0")"
pwd
(
cd ../Jellyfin.Plugin.SmartPlaylist/
dotnet build
)
pwd
mkdir -p ./cache ./media ./config/plugins/jellyfin-smart-playlist
cp ../Jellyfin.Plugin.SmartPlaylist/bin/Debug/net8.0/jellyfin-smart-playlist.dll ./config/plugins/jellyfin-smart-playlist/
docker pull "$JELLYFIN"
docker run --rm --user "$(id -u):$(id -g)" \
-v ./cache:/cache \
-v ./config:/config \
-v ./media:/media \
-p 8096:8096 \
"$JELLYFIN"

View file

@ -1 +0,0 @@
global using Xunit;

View file

@ -1,233 +0,0 @@
using Lisp_Boolean = Jellyfin.Plugin.SmartPlaylist.Lisp.Boolean;
using Lisp_Object = Jellyfin.Plugin.SmartPlaylist.Lisp.Object;
using Jellyfin.Plugin.SmartPlaylist.Lisp;
using Jellyfin.Plugin.SmartPlaylist.Lisp.Compiler;
namespace Tests
{
public class O {
int _i;
bool _b;
public O(int i, bool b) {
_i = i;
_b = b;
}
public int i { get => _i; }
public bool b { get => _b; }
public int I() {
return _i;
}
}
public class Test {
[Fact]
public static void TestTokenizer() {
StringTokenStream sts = StringTokenStream.generate("(\"some literal string\" def ghj +100 -+300 1 >= ++ !=)");
Assert.Equal("(", sts.Get().value);
Assert.Equal("\"", sts.Get().value);
Assert.Equal("some", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("literal", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("string", sts.Get().value);
Assert.Equal("\"", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("def", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("ghj", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("+100", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("-+300", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("1", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal(">=", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("++", sts.Get().value);
Assert.Equal(" ", sts.Get().value);
Assert.Equal("!=", sts.Get().value);
Assert.Equal(")", sts.Get().value);
sts.Commit();
Assert.Equal(0, sts.Available());
}
[Fact]
public static void TestParser() {
string program = "(+ 1 (* 2 3))";
StringTokenStream sts = StringTokenStream.generate(program);
Parser p = new Parser(sts);
Assert.Equal(program, string.Format("{0}", p.parse()));
program = "(haskeys o \"i\" \"b\")";
sts = StringTokenStream.generate(program);
p = new Parser(sts);
Assert.Equal(program, string.Format("{0}", p.parse()));
}
[Fact]
public static void TestFunctions() {
Executor e = new Executor();
Assert.Equal("(1 2 3)", e.eval("(quote (1 2 3))").ToString());
Assert.Equal("abc", e.eval("(quote abc)").ToString());
Assert.Equal("t", e.eval("(atom 1)").ToString());
Assert.Equal("nil", e.eval("(atom (quote (1 2 3)))").ToString());
Assert.Equal("t", e.eval("(eq 2 2)").ToString());
Assert.Equal("nil", e.eval("(eq 2 3)").ToString());
Assert.Equal("1", e.eval("(car (quote (1 2 3)))").ToString());
Assert.Equal("(2 3)", e.eval("(cdr (quote (1 2 3)))").ToString());
Assert.Equal("(1 . 2)", e.eval("(cons 1 2)").ToString());
Assert.Equal("(1 2)", e.eval("(cons 1 (cons 2 nil))").ToString());
Assert.Equal("(1)", e.eval("(cons 1 nil)").ToString());
Assert.Equal("(1)", e.eval("(cons 1 ())").ToString());
Assert.Equal("\"Case 2\"", e.eval("""
(cond
((eq 1 2) "Case 1")
((eq 2 2) "Case 2"))
""").ToString());
Assert.Equal("\"Case 1\"", e.eval("""
(cond
((eq 2 2) "Case 1")
((eq 2 2) "Case 2"))
""").ToString());
Assert.Equal("nil", e.eval("""
(cond
((eq 1 2) "Case 1")
((eq 3 2) "Case 2"))
""").ToString());
Assert.Equal("t", e.eval("((lambda (a) (eq a a)) 2)").ToString());
Assert.Equal("t", e.eval("(begin (car (quote (nil 1))) t)").ToString());
Assert.Equal("(1)", e.eval("(begin t (cdr (quote (nil 1))))").ToString());
Assert.Equal("t", e.eval("""
(begin
(define abc 10)
(eq abc abc))
""").ToString());
Assert.Equal("1", e.eval("""
(begin
(define if (lambda (condition a b) (
cond (condition a) (t b))))
(if (> 2 1) (car (quote (1 2 3))) (cdr (quote (2 3 4)))))
""").ToString());
Assert.Equal("(3 4)", e.eval("""
(begin
(define if (lambda (condition a b) (
cond (condition a) (t b))))
(if (> 0 1) (car (quote (1 2 3))) (cdr (quote (2 3 4)))))
""").ToString());
}
[Fact]
public static void TestFunctionsAdvanced() {
Executor e = new Executor();
Assert.Equal("2", e.eval("""
((lambda (b) b) (car (quote (2 3))))
""").ToString());
Assert.Equal("(3 4 5)", e.eval("""
((lambda (x y . z) z) 1 2 3 4 5)
""").ToString());
Assert.Equal("3", e.eval("""
(begin
(define if (lambda (condition a b) (cond (condition a) (t b))))
(if (< 1 2) 3 2))
""").ToString());
Assert.Equal("2", e.eval("""
(begin
(define if (lambda (condition a b) (cond (condition a) (t b))))
(if (> 1 2) 3 2))
""").ToString());
Assert.Equal("1", e.eval("""
(begin
(define if (lambda* (condition a b) (
cond ((eval condition) (eval a)) (t (eval b)))))
(if (> 2 1) (car (quote (1 2 3))) (cdr (quote (2 3 4)))))
""").ToString());
Assert.Equal("(3 4)", e.eval("""
(begin
(define if (lambda* (condition a b) (
cond ((eval condition) (eval a)) (t (eval b)))))
(if (> 0 1) (car (quote (1 2 3))) (cdr (quote (2 3 4)))))
""").ToString());
Assert.Equal("120", e.eval("""
(begin
(define f (lambda (n) (cond ((<= n 1) 1) (t (* n (f (- n 1)))))))
(f 5))
""").ToString());
Assert.Equal("120", e.eval("""
(begin
(define if (lambda* (condition a b) (
cond ((eval condition) (eval a)) (t (eval b)))))
(define f (lambda (n) (if (<= n 1) 1 (* n (f (- n 1))))))
(f 5))
""").ToString());
Assert.Equal("(1 2 3 4 5)", e.eval("""
(begin
(define if (lambda* (condition a b) (
cond ((eval condition) (eval a)) (t (eval b)))))
((lambda (. args) args) 1 2 3 4 5))
""").ToString());
Assert.Equal("t", e.eval("""
(begin
(define null (lambda* (x) (
cond ((eval x) nil) (t t))))
(null nil))
""").ToString());
Assert.Equal("nil", e.eval("""
(begin
(define null (lambda* (x) (cond ((eval x) nil) (t t))))
(null (quote (1 2))))
""").ToString());
}
[Fact]
public static void ObjectTest() {
Executor e = new Executor();
Expression r;
e.environment.Set("o", Lisp_Object.FromBase(new O(5, false)));
r = e.eval("""(haskeys o "i" "b")""");
Assert.True(((Lisp_Boolean)r).Value());
r = e.eval("""(getitems o "i" "b")""");
Assert.Equal("(5 nil)", string.Format("{0}", r));
r = e.eval("""(invoke o "I" nil)""");
Assert.Equal("5", string.Format("{0}", r));
}
[Fact]
public static void DefaultEnvironmentTest() {
Executor e = new Executor(new DefaultEnvironment());
Assert.Equal("1", e.eval("(if nil 0 1)").ToString());
Assert.Equal("0", e.eval("(if t 0 1)").ToString());
Assert.Equal("5", e.eval("(if t (if t 5 nil) nil)").ToString());
Assert.Equal("nil", e.eval("(if t (if nil 5 nil) nil)").ToString());
Assert.Equal("(1 2 3)", e.eval("(list 1 2 3)").ToString());
Assert.Equal("3", e.eval("(find 3 (list 1 2 3 4))").ToString());
Assert.Equal("nil", e.eval("(find 0 (list 1 2 3 4))").ToString());
Assert.Equal("(2 4 6)", e.eval("(map (lambda (x) (* x 2)) (quote (1 2 3)))").ToString());
Assert.Equal("nil", e.eval("(and 1 2 3 nil)").ToString());
Assert.Equal("t", e.eval("(and t t t t)").ToString());
Assert.Equal("t", e.eval("(or nil nil t nil)").ToString());
Assert.Equal("nil", e.eval("(or nil nil nil nil)").ToString());
Assert.Equal("t", e.eval("(any (lambda (x) (= x 2)) (list 1 2 3 4 5 6))").ToString());
Assert.Equal("nil", e.eval("(any (lambda (x) (= x 2)) (list 1 3 4 5 6))").ToString());
Assert.Equal("nil", e.eval("(any (lambda (x) (= x 2)) nil)").ToString());
Assert.Equal("t", e.eval("(all (lambda (x) (= 1 (% x 2))) (list 1 3 5))").ToString());
Assert.Equal("nil", e.eval("(all (lambda (x) (= 1 (% x 2))) (list 1 3 4 5))").ToString());
Assert.Equal("nil", e.eval("(all (lambda (x) (= x 2)) nil)").ToString());
Assert.Equal("10", e.eval("(fold (lambda (a b) (+ a b)) 0 (list 1 2 3 4))").ToString());
Assert.Equal("(2 3 4 5 6 7)", e.eval("(append (list 2 3 4) (list 5 6 7))").ToString());
Assert.Equal("(1 2 3 4 5 6 7)", e.eval("(qsort (lambda (a b) (> a b)) (list 5 4 7 3 2 6 1))").ToString());
}
}
}

View file

@ -1,27 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Jellyfin.Plugin.SmartPlaylist/jellyfin-smart-playlist.csproj" />
</ItemGroup>
</Project>

View file

@ -1,117 +0,0 @@
---
resource_types:
- name: http-resource
type: registry-image
source:
repository: redxef/concourse-http-resource
tag: edge
resources:
- name: source
type: git
source:
uri: https://gitea.redxef.at/redxef/jellyfin-smart-playlist
branch: main
fetch_tags: true
tag_regex: 'v.*'
- name: manifest
type: git
source:
uri: ssh://git@gitea.redxef.at:8022/redxef/jellyfin-smart-playlist.git
branch: manifest
private_key: ((gitea.id_ed25519))
- name: releases
type: http-resource
source:
url: https://gitea.redxef.at/api/v1/repos/redxef/jellyfin-smart-playlist/releases
method: get
auth:
basic:
username: ((gitea.username))
password: ((gitea.token))
- name: artifact
type: http-resource
source:
url: https://gitea.redxef.at/api/v1/repos/redxef/jellyfin-smart-playlist/releases/((.:release_id))/assets
method: get
auth:
basic:
username: ((gitea.username))
password: ((gitea.token))
headers:
- - Accept
- application/json
query:
- - name
- smart-playlist_((.:version)).zip
body:
multipart:
files:
attachment: artifacts/smart-playlist_((.:version)).zip
version_check_method: none
jobs:
- name: release
plan:
- get: source
trigger: true
- get: manifest
- get: releases
- task: run-build
config:
platform: linux
image_resource:
type: registry-image
source:
repository: alpine
inputs:
- name: source
- name: manifest
- name: releases
outputs:
- name: artifacts
- name: manifest
run:
path: sh
args:
- -c
- |
#!/bin/sh
set -eu
apk add --no-cache jq git dotnet8-sdk python3 py3-pip
pip3 install --break-system-packages jprm
cp manifest/manifest.json source/
(
cd source
./release.sh build
)
cp source/artifacts/*.zip artifacts/
cd source
VERSION="$(./release.sh version)"
cd ..
printf '%s' "$VERSION" > artifacts/version
cp source/manifest.json manifest/
(
cd manifest
git add .
git config user.name 'Concourse CI/CD'
git config user.email 'concourse@redxef.at'
git commit -m "ci: update manifest for version ${VERSION}."
)
jq --arg tag "v$VERSION" -r '.[] | select(.tag_name == $tag) | .id' < releases/body > artifacts/release_id
ls artifacts
- load_var: release_id
file: artifacts/release_id
reveal: true
- load_var: version
file: artifacts/version
reveal: true
- put: artifact
inputs:
- artifacts
params:
method: post
- put: manifest
params:
repository: manifest

View file

@ -1,27 +0,0 @@
# Examples
- `Favourite Pop`: A playlist
containing all favourite items of the genre pop.
```
Id: Favourite Pop
Name: Favourite Pop
Program: |
(and (is-type "Audio") (is-favorite) (is-genre "pop" (genre-list)))
```
- `Electro Swing`: A playlist containing all items
which have a genre that contains "electro" and a
genre that contains "swing". It will only include
albums and single tracks.
```
Id: Electro Swing
Name: Electro Swing
Program: |
(let
(g (genre-list))
(and
(or
(is-type "Audio")
(is-type "MusicAlbum"))
(is-genre "electro" g)
(is-genre "swing" g)))
```

60
manifest.json Normal file
View file

@ -0,0 +1,60 @@
[
{
"guid": "dd2326e3-4d3e-4bfc-80e6-28502c1131df",
"name": "Smart Playlist",
"description": "Create smart playlists with a Lisp filter engine.\n\nThe same playlist definition can be used for multiple users.\n",
"overview": "Smart playlists with Lisp filter engine.",
"owner": "redxef",
"category": "General",
"versions": [
{
"version": "0.3.0.0",
"changelog": "## v0.3.0.0\n- Add a second program (`SortProgram`) which is run after the filtering, this\n program should return the list of items, but in the order in which they should appear in\n the playlist. The default is `(begin items)` which returns the list as is.\n- Extend builtin lisp definitions: add `qsort` and string comparison methods\n- Extend default program definitions: add `all-genres` and `any-genres` to quickly specify a list of genres which to include (or excluding when negating)\n- Update Jellyfin to v 10.10.3\n\n**Fixes**:\n- The progress report now correctly gives a percentage in the range [0, 100].\n\n## v0.2.2.0\n- Update Jellyfin to v 10.10.2\n\n## v0.2.1.0\n- Make default program configuration a textarea in the settings page\n- Add convinience definitions: `is-type`, `name-contains`\n- Update YamlDotNet to v 16.2.0\n\n**Fixes**:\n- The default program was malformed, a closing bracket was at the wrong position\n- The `haskeys` function could only be called on Objects\n\n## v0.2.0.0\n- Switch to yaml loading, old json files are still accepted\n- Rework lisp interpreter to be more conventional\n- Use arbitrary strings as ids for playlists\n- Add configuration page with some default definitions for\n the filter expressions.\n\n**Breaking Changes**:\n- The lisp interpreter will now only detect strings in double quotes (`\"`).\n- The interpreter will also not allow specifying lists without quoting them.\n `(1 2 3)` ... used to work but will no longer, replace by either specifying\n the list as `(list 1 2 3)` or `(quote (1 2 3))`.\n\n## v0.1.1.0\n- Initial Alpha release.\n",
"targetAbi": "10.10.3.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.3.0.0/smart-playlist_0.3.0.0.zip",
"checksum": "6011b6f34452960d5122797df161f791",
"timestamp": "2024-11-24T22:36:29Z"
},
{
"version": "0.2.2.0",
"changelog": "## v0.2.2.0\n- Update Jellyfin to v 10.10.2\n\n## v0.2.1.0\n- Make default program configuration a textarea in the settings page\n- Add convinience definitions: `is-type`, `name-contains`\n- Update YamlDotNet to v 16.2.0\n\n**Fixes**:\n- The default program was malformed, a closing bracket was at the wrong position\n- The `haskeys` function could only be called on Objects\n\n## v0.2.0.0\n- Switch to yaml loading, old json files are still accepted\n- Rework lisp interpreter to be more conventional\n- Use arbitrary strings as ids for playlists\n- Add configuration page with some default definitions for\n the filter expressions.\n\n**Breaking Changes:**\n- The lisp interpreter will now only detect strings in double quotes (`\"`).\n- The interpreter will also not allow specifying lists without quoting them.\n `(1 2 3)` ... used to work but will no longer, replace by either specifying\n the list as `(list 1 2 3)` or `(quote (1 2 3))`.\n\n## v0.1.1.0\n- Initial Alpha release.\n",
"targetAbi": "10.10.2.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.2.2.0/smart-playlist_0.2.2.0.zip",
"checksum": "d41d77cb56c058c41ee6dbcfd2112a31",
"timestamp": "2024-11-18T20:02:36Z"
},
{
"version": "0.2.1.0",
"changelog": "## v0.2.1.0\n- Make default program configuration a textarea in the settings page\n- Add convinience definitions: `is-type`, `name-contains`\n- Update YamlDotNet to v 16.2.0\n\n**Fixes**:\n- The default program was malformed, a closing bracket was at the wrong position\n- The `haskeys` function could only be called on Objects\n\n## v0.2.0.0\n- Switch to yaml loading, old json files are still accepted\n- Rework lisp interpreter to be more conventional\n- Use arbitrary strings as ids for playlists\n- Add configuration page with some default definitions for\n the filter expressions.\n\n**Breaking Changes:**\n- The lisp interpreter will now only detect strings in double quotes (`\"`).\n- The interpreter will also not allow specifying lists without quoting them.\n `(1 2 3)` ... used to work but will no longer, replace by either specifying\n the list as `(list 1 2 3)` or `(quote (1 2 3))`.\n\n## v0.1.1.0\n- Initial Alpha release.\n",
"targetAbi": "10.10.0.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.2.1.0/smart-playlist_0.2.1.0.zip",
"checksum": "14e40e271cf94a6612e06ea0cced4c94",
"timestamp": "2024-11-11T17:21:58Z"
},
{
"version": "0.2.0.0",
"changelog": "## v0.2.0.0\n- Switch to yaml loading, old json files are still accepted\n- Rework lisp interpreter to be more conventional\n- Use arbitrary strings as ids for playlists\n- Add configuration page with some default definitions for\n the filter expressions.\n\n**Breaking Changes:**\n- The lisp interpreter will no only detect strings in double quotes (`\"`).\n- The interpreter will also not allow specifying lists without quoting them.\n `(1 2 3)` ... used to work but will no longer, replace by either specifying\n the list as `(list 1 2 3)` or (quote (1 2 3)).\n\n## v0.1.1.0\n- Initial Alpha release.\n",
"targetAbi": "10.10.0.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.2.0.0/smart-playlist_0.2.0.0.zip",
"checksum": "f06603c85c6b12a1ffbe3967290ed54b",
"timestamp": "2024-11-08T19:44:27Z"
},
{
"version": "0.1.1.0",
"changelog": "- Initial Alpha release.\n",
"targetAbi": "10.10.0.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.1.1.0/smart-playlist_0.1.1.0.zip",
"checksum": "1f2246097b9c2550c0208282765ed856",
"timestamp": "2024-10-30T14:32:28Z"
},
{
"version": "0.1.0.0",
"changelog": "- Initial Alpha release.\n",
"targetAbi": "10.10.0.0",
"sourceUrl": "https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v0.1.0.0/smart-playlist_0.1.0.0.zip",
"checksum": "d11b2ef8f328ed1143d95657cae33a02",
"timestamp": "2024-10-30T02:16:48Z"
}
]
}
]

View file

@ -1,23 +0,0 @@
#!/bin/sh
JPRM="jprm"
PLUGIN=Jellyfin.Plugin.SmartPlaylist
VERSION=$(sed -n '/^version:/ s/^version: *//p' "${PLUGIN}/build.yaml")
ARTIFACT_DIR=artifacts
REPO_URL="https://gitea.redxef.at/redxef/jellyfin-smart-playlist/releases/download/v${VERSION}/smart-playlist_${VERSION}.zip"
build() {
mkdir -p "${ARTIFACT_DIR}"
find "${PLUGIN}" -name project.assets.json -exec rm -v '{}' ';'
zipfile=$($JPRM --verbosity=debug plugin build "${PLUGIN}" --output="${ARTIFACT_DIR}" --version="${VERSION}") && {
$JPRM --verbosity=debug repo add --plugin-url="${REPO_URL}" . "${zipfile}"
}
}
version() {
echo "$VERSION"
}
"$@"
exit $?