forked from trav/lintunes
Add smart playlists with full iTunes 12 import (Phase 1)
Auto-populating, criteria-driven playlists that import faithfully from iTunes. - lintunes/smart.py: recursive SmartCriteria/SmartGroup/SmartRule/SmartLimit model (JSON round-tripping), a shared FIELD_REGISTRY used by both the evaluator and the editor, and evaluate() (match all/any, nested groups, string/int/duration/rating/date/bool ops, "in the last N", limit by items/time/size). Null play/skip dates are treated as the distant past, matching iTunes. - iTunes import via a vendored MIT-licensed binary parser (lintunes/itunes_smart/, from cvzi/itunes_smartplaylist). Nested groups parse and evaluate; blobs we can't represent (MediaKind/iCloud/etc.) flag unsupported and keep the imported snapshot. "loved" is dropped per user pref. - library_manager: create/set/recompute smart playlists (undoable), field-scoped coalesced live recompute hooked into the edit/play/skip/add funnels, a no-op equality guard to avoid Syncthing churn, and manual-edit guards. main.py recomputes on load; conflict_resolver keeps newest criteria for smart lists. - GUI: ❧ glyph painted in the sidebar branch column, read-only track table for smart playlists, New/Edit Smart Playlist menus, and SmartPlaylistEditorDialog (per-field rule rows, match all/any, limits, live updating). Tests: tests/test_round14.py (real captured blobs in tests/smart_blobs.json).
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) cuzi 2018
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Vendored iTunes smart-playlist criteria parser.
|
||||
|
||||
This package is a vendored copy of `itunessmart` by cuzi
|
||||
(https://github.com/cvzi/itunes_smartplaylist), used under the MIT License
|
||||
(see the bundled LICENSE file). It decodes the base64 "Smart Info" / "Smart
|
||||
Criteria" binary blobs from an iTunes XML library into a structured rule tree.
|
||||
|
||||
Vendored rather than pip-installed so LinTunes stays self-contained for an
|
||||
offline, Syncthing-synced desktop app. Only the import line in parse.py was
|
||||
changed (to a package-relative import); the parsing logic is unmodified.
|
||||
|
||||
LinTunes code should not use this package directly -- go through
|
||||
`lintunes.smart.parse_itunes_smart()`, which converts the parser's output into
|
||||
LinTunes' own `SmartCriteria` model.
|
||||
"""
|
||||
|
||||
from lintunes.itunes_smart.parse import SmartPlaylistParser, SmartPlaylist
|
||||
|
||||
__all__ = ["SmartPlaylistParser", "SmartPlaylist"]
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
Module holding static data related to the iTunes playlist format.
|
||||
"""
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class FileKind:
|
||||
def __init__(self, name, extension):
|
||||
self.name = name
|
||||
self.extension = extension
|
||||
|
||||
|
||||
FileKinds = [
|
||||
FileKind("Protected AAC audio file", ".m4p"),
|
||||
FileKind("Purchased AAC audio file", ".m4a"),
|
||||
FileKind("Apple Lossless audio file", ".m4a"),
|
||||
FileKind("MPEG audio file", ".mp3"),
|
||||
FileKind("AIFF audio file", ".aiff"),
|
||||
FileKind("WAV audio file", ".wav"),
|
||||
FileKind("QuickTime movie file", ".mov"),
|
||||
FileKind("MPEG-4 video file", ".mp4"),
|
||||
FileKind("Purchased MPEG-4 video file", ".mp4"),
|
||||
FileKind("AAC audio file", ".m4a")
|
||||
]
|
||||
|
||||
MediaKinds = {
|
||||
0x01: "Music",
|
||||
0x02: "Movie",
|
||||
0x04: "Podcast",
|
||||
0x08: "Audiobook",
|
||||
0x20: "Music Video",
|
||||
0x40: "TV Show",
|
||||
0x400: "Home Video",
|
||||
0x10000: "iTunes Extras",
|
||||
0x100000: "Voice Memo", # TODO "Voice Memo" might be 0x00 on Apple Music
|
||||
0x200000: "iTunes U",
|
||||
0xC00000: "Book",
|
||||
# TODO mediakinds of toplevel playlists
|
||||
# The following are only used in the toplevel playlists: Music, TV Shows, Movies and Books
|
||||
# (These playlists can be selected with the arrows or from a dropdown menu in iTunes 12)
|
||||
# Theses Media Kinds cannot be selected by the user. I am unsure about their meaning.
|
||||
0xC00008: "Book or Audiobook", # TODO My guess: This contains Books and Audiobooks
|
||||
0x1021B1: "Music", # TODO My guess: This is similar to Music
|
||||
0x208004: "Undesired Music", # TODO My guess: This is some kind of Music that should not appear in the toplevel playlist
|
||||
0x20A004: "Undesired Other" # TODO My guess: This is something (other than music) that should not appear in the toplevel playlist
|
||||
}
|
||||
|
||||
iCloudStatus = {
|
||||
0x01: "Purchased",
|
||||
0x02: "Matched",
|
||||
0x03: "Uploaded",
|
||||
0x04: "Ineligible",
|
||||
0x05: "Local Only",
|
||||
0x07: "Duplicate",
|
||||
0x09: "No Longer Available",
|
||||
}
|
||||
|
||||
LoveStatus = {
|
||||
0x00: "None",
|
||||
0x02: "Loved",
|
||||
0x03: "Disliked",
|
||||
}
|
||||
|
||||
LocationKinds = {
|
||||
0x01: "Computer",
|
||||
0x10: "iCloud"
|
||||
}
|
||||
|
||||
SelectionMethodsStrings = {
|
||||
"Random": ["random", "RANDOM()"],
|
||||
"Name": ["name", "SortName"],
|
||||
"Album": ["album", "SortAlbum"],
|
||||
"Artist": ["artist", "SortArtist"],
|
||||
"Genre": ["genre", "Genre"],
|
||||
"HighestRating": ["highest rated", "Rating DESC"],
|
||||
"LowestRating": ["lowest rated", "Rating ASC"],
|
||||
"RecentlyPlayed": [["most recently played", "least recently played"], ["LastPlayed DESC", "LastPlayed ASC"]],
|
||||
"OftenPlayed": [["most often played", "least often played"], ["Plays DESC", "Plays ASC"]],
|
||||
"RecentlyAdded": [["most recently added", "least recently added"], ["DateAdded DESC", "DateAdded ASC"]]
|
||||
}
|
||||
|
||||
|
||||
DateStartFromUnix = -2082844800 # iTunes/Unix time stamp 0 difference
|
||||
|
||||
|
||||
class LimitMethods(IntEnum):
|
||||
"""The methods by which the number of songs in a playlist are limited"""
|
||||
Minutes = 0x01
|
||||
MB = 0x02
|
||||
Items = 0x03
|
||||
Hours = 0x04
|
||||
GB = 0x05
|
||||
|
||||
|
||||
class SelectionMethods(IntEnum):
|
||||
"""The methods by which songs are selected for inclusion in a limited playlist"""
|
||||
Random = 0x02
|
||||
Name = 0x05
|
||||
Album = 0x06
|
||||
Artist = 0x07
|
||||
Genre = 0x09
|
||||
HighestRating = 0x1c
|
||||
LowestRating = 0x01
|
||||
RecentlyPlayed = 0x1a
|
||||
OftenPlayed = 0x19
|
||||
RecentlyAdded = 0x15
|
||||
|
||||
|
||||
class StringFields(IntEnum):
|
||||
"""The matching criteria which take string data"""
|
||||
Album = 0x03
|
||||
AlbumArtist = 0x47
|
||||
Artist = 0x04
|
||||
Category = 0x37
|
||||
Comments = 0x0e
|
||||
Composer = 0x12
|
||||
Description = 0x36
|
||||
Genre = 0x08
|
||||
Grouping = 0x27
|
||||
Kind = 0x09
|
||||
Name = 0x02
|
||||
Show = 0x3e
|
||||
SortAlbum = 0x4f
|
||||
SortAlbumartist = 0x51
|
||||
SortComposer = 0x52
|
||||
SortName = 0x4e
|
||||
SortShow = 0x53
|
||||
VideoRating = 0x59
|
||||
|
||||
|
||||
class IntFields(IntEnum):
|
||||
"""The matching criteria which take integer data"""
|
||||
BPM = 0x23
|
||||
BitRate = 0x05
|
||||
Compilation = 0x1f
|
||||
DiskNumber = 0x18
|
||||
Plays = 0x16
|
||||
Rating = 0x19
|
||||
Podcast = 0x39
|
||||
SampleRate = 0x06
|
||||
Season = 0x3f
|
||||
Size = 0x0c
|
||||
Skips = 0x44
|
||||
Duration = 0x0d
|
||||
TrackNumber = 0x0b
|
||||
Year = 0x07
|
||||
|
||||
|
||||
class BooleanFields(IntEnum):
|
||||
"""The matching criteria which take boolean data"""
|
||||
HasArtwork = 0x25
|
||||
Purchased = 0x29
|
||||
Checked = 0x1d
|
||||
|
||||
|
||||
class DateFields(IntEnum):
|
||||
"""The matching criteria which take date data"""
|
||||
DateAdded = 0x10
|
||||
DateModified = 0x0a
|
||||
LastPlayed = 0x17
|
||||
LastSkipped = 0x45
|
||||
|
||||
|
||||
class MediaKindFields(IntEnum):
|
||||
"""The matching criteria which take a Media Kind, as defined above"""
|
||||
MediaKind = 0x3c
|
||||
|
||||
|
||||
class PlaylistFields(IntEnum):
|
||||
"""The matching criteria which take a Persistent Playlist ID (64bit)"""
|
||||
PlaylistPersistentID = 0x28
|
||||
|
||||
|
||||
class LoveFields(IntEnum):
|
||||
"""The matching criteria which take a Persistent Playlist ID (64bit)"""
|
||||
Love = 0x9a
|
||||
|
||||
|
||||
class CloudFields(IntEnum):
|
||||
"""The matching criteria which take iCloud status , as defined above """
|
||||
iCloudStatus = 0x86
|
||||
|
||||
|
||||
class LocationFields(IntEnum):
|
||||
"""The matching criteria which take a Location, as defined above"""
|
||||
Location = 0x85
|
||||
|
||||
|
||||
class LogicSign(IntEnum):
|
||||
"""The signs which apply to different kinds of logic (is vs. is not, contains vs. doesn't contain, etc.)"""
|
||||
IntPositive = 0x00
|
||||
StringPositive = 0x01
|
||||
IntNegative = 0x02
|
||||
StringNegative = 0x03
|
||||
|
||||
|
||||
class LogicRule(IntEnum):
|
||||
"""The logical rules"""
|
||||
Other = 0x00
|
||||
Is = 0x01
|
||||
Contains = 0x02
|
||||
Starts = 0x04
|
||||
Ends = 0x08
|
||||
Greater = 0x10
|
||||
Less = 0x40
|
||||
|
||||
|
||||
class Offset(IntEnum):
|
||||
"""Byte offsets for the fields"""
|
||||
INTLENGTH = 67 # The length on a int criteria starting at the first int
|
||||
SUBEXPRESSIONLENGTH = 192 # The length of a subexpression starting from FIELD
|
||||
|
||||
# INFO OFFSETS
|
||||
# Offsets for bytes which...
|
||||
LIVEUPDATE = 0 # determine whether live updating is enabled - Absolute offset
|
||||
MATCHBOOL = 1 # determine whether logical matching is to be performed - Absolute offset
|
||||
LIMITBOOL = 2 # determine whether results are limited - Absolute offset
|
||||
LIMITMETHOD = 3 # determine by what criteria the results are limited - Absolute offset
|
||||
SELECTIONMETHOD = 7 # determine by what criteria limited playlists are populated - Absolute offset
|
||||
LIMITINT = 8 # determine the limited - Absolute offset
|
||||
LIMITCHECKED = 12 # determine whether to exclude unchecked items - Absolute offset
|
||||
SELECTIONMETHODSIGN = 13 # determine whether certain selection methods are "most" or "least" - Absolute offset
|
||||
|
||||
# CRITERIA OFFSETS
|
||||
# Offsets for bytes which...
|
||||
LOGICTYPE = 15 # determine whether all or any criteria must match - Absolute offset
|
||||
FIELD = 139 # determine what is being matched (Artist, Album, &c) - Absolute offset
|
||||
LOGICSIGN = 1 # determine whether the matching rule is positive or negative (e.g., is vs. is not) - Relative offset from FIELD
|
||||
LOGICRULE = 4 # determine the kind of logic used (is, contains, begins, &c) - Relative offset from FIELD
|
||||
STRING = 54 # begin string data - Relative offset from FIELD
|
||||
INTA = 57 # begin the first int - Relative offset from FIELD
|
||||
INTB = 24 # begin the second int - Relative offset from INTA
|
||||
TIMEMULTIPLE = 73 # begin the int with the multiple of time - Relative offset from FIELD
|
||||
TIMEVALUE = 65 # begin the inverse int with the value of time - Relative offset from FIELD
|
||||
SUBLOGICTYPE = 68 # determine whether all or any criteria must match - Relative offset from FIELD
|
||||
SUBINT = 61 # begin the first int - Relative offset from FIELD
|
||||
@@ -0,0 +1,843 @@
|
||||
"""
|
||||
Module holding the parsing algorithm
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
import base64
|
||||
import datetime
|
||||
import struct
|
||||
import json
|
||||
import re
|
||||
from lintunes.itunes_smart.data_structure import *
|
||||
|
||||
|
||||
class SmartPlaylist:
|
||||
""" Parser result. Contains all decoded playlist data"""
|
||||
|
||||
def __init__(self, parser):
|
||||
self.output = parser.output
|
||||
self.query = parser.query
|
||||
self.queryTree = parser.queryTree
|
||||
self.ignore = parser.ignore
|
||||
|
||||
def __str__(self):
|
||||
return "SmartPlaylist(`%s`)" % self.query
|
||||
|
||||
def __repr__(self):
|
||||
return "SmartPlaylist(%s)" % json.dumps({"queryTree": self.queryTree, "ignore": self.ignore}, indent=2)
|
||||
|
||||
|
||||
class SmartPlaylistParser:
|
||||
def __init__(self, datastr_info=None, datastr_criteria=None):
|
||||
self.is_parsed = False
|
||||
if datastr_info and datastr_criteria:
|
||||
self.str_data(datastr_info, datastr_criteria)
|
||||
self.parse()
|
||||
|
||||
def str_data(self, datastr_info, datastr_criteria):
|
||||
i = base64.standard_b64decode("".join(datastr_info.split()))
|
||||
c = base64.standard_b64decode("".join(datastr_criteria.split()))
|
||||
return self.data(i, c)
|
||||
|
||||
def data(self, data_info, data_criteria):
|
||||
self.is_parsed = False
|
||||
self.info = data_info
|
||||
self.criteria = data_criteria
|
||||
self.query = ""
|
||||
self.root = {}
|
||||
self.queryTree = self.root
|
||||
self.queryTreeCurrent = []
|
||||
self.fullTreeRoot = {}
|
||||
self.fullTree = self.fullTreeRoot
|
||||
self.fullTreeCurrent = []
|
||||
self.output = ""
|
||||
self.ignore = ""
|
||||
self.limit = {}
|
||||
|
||||
self.subStack = []
|
||||
|
||||
def result(self):
|
||||
if self.is_parsed:
|
||||
return SmartPlaylist(self)
|
||||
raise RuntimeError("Data not parsed yet. Call parse() before result()")
|
||||
|
||||
def parse(self):
|
||||
if self.is_parsed:
|
||||
return
|
||||
|
||||
if not hasattr(self, 'info') or not hasattr(self, 'criteria') or not self.info or not self.criteria: # pragma: no cover
|
||||
raise RuntimeError("Set smart info with data() or strdata() before running parse()")
|
||||
|
||||
self.offset = int(Offset.FIELD)
|
||||
|
||||
if self.info[Offset.MATCHBOOL] == 1:
|
||||
self.current_operator = self._operatorFromLogicType(self.criteria[Offset.LOGICTYPE])
|
||||
self.queryTree[self.current_operator] = self.queryTreeCurrent
|
||||
self.fullTree[self.current_operator] = self.fullTreeCurrent
|
||||
|
||||
while True:
|
||||
self.again = False
|
||||
|
||||
if len(self.subStack) > 0:
|
||||
if self.subStack[-1]["N"] == 0:
|
||||
old = self.subStack.pop()
|
||||
|
||||
self.current_operator = old["operator"]
|
||||
self.queryTreeCurrent = old["queryTreeCurrent"]
|
||||
self.fullTreeCurrent = old["fullTreeCurrent"]
|
||||
else:
|
||||
self.subStack[-1]["N"] -= 1
|
||||
|
||||
self.logicSignOffset = self.offset + int(Offset.LOGICSIGN)
|
||||
self.logicRulesOffset = self.offset + int(Offset.LOGICRULE)
|
||||
self.stringOffset = self.offset + int(Offset.STRING)
|
||||
self.intAOffset = self.offset + int(Offset.INTA)
|
||||
self.intBOffset = self.intAOffset + int(Offset.INTB)
|
||||
self.timeMultipleOffset = self.offset + \
|
||||
int(Offset.TIMEMULTIPLE)
|
||||
self.timeValueOffset = self.offset + int(Offset.TIMEVALUE)
|
||||
|
||||
if any(self.criteria[self.offset] ==
|
||||
e.value for e in StringFields):
|
||||
self.ProcessStringField()
|
||||
elif any(self.criteria[self.offset] == e.value for e in IntFields):
|
||||
self.ProcessIntField()
|
||||
elif any(self.criteria[self.offset] == e.value for e in DateFields):
|
||||
self.ProcessDateField()
|
||||
elif any(self.criteria[self.offset] == e.value for e in BooleanFields):
|
||||
self.ProcessBooleanField()
|
||||
elif any(self.criteria[self.offset] == e.value for e in MediaKindFields):
|
||||
self.ProcessListField(MediaKindFields, MediaKinds, listtype="mediakind")
|
||||
elif any(self.criteria[self.offset] == e.value for e in PlaylistFields):
|
||||
self.ProcessPlaylistField()
|
||||
elif any(self.criteria[self.offset] == e.value for e in CloudFields):
|
||||
self.ProcessListField(CloudFields, iCloudStatus, listtype="cloud")
|
||||
elif any(self.criteria[self.offset] == e.value for e in LoveFields):
|
||||
self.ProcessListField(LoveFields, LoveStatus, listtype="love")
|
||||
elif any(self.criteria[self.offset] == e.value for e in LocationFields):
|
||||
self.ProcessListField(LocationFields, LocationKinds, listtype="location")
|
||||
elif self.criteria[self.offset] == 0:
|
||||
# Subexpression
|
||||
|
||||
parent_operator = self.current_operator
|
||||
subgroup_operator = self._operatorFromLogicType(self.criteria[self.offset + Offset.SUBLOGICTYPE])
|
||||
|
||||
numberOfSubExpression = self._iTunesUint(
|
||||
self.criteria[self.offset + Offset.SUBINT:self.offset + Offset.SUBINT + 4])
|
||||
|
||||
self.subStack.append({
|
||||
"N": numberOfSubExpression,
|
||||
"operator": parent_operator,
|
||||
"queryTreeCurrent": self.queryTreeCurrent,
|
||||
"fullTreeCurrent": self.fullTreeCurrent,
|
||||
})
|
||||
|
||||
newtree = {}
|
||||
newcurrent = []
|
||||
self.queryTreeCurrent.append(newtree)
|
||||
|
||||
newfulltree = {}
|
||||
newfulltreecurrent = []
|
||||
self.fullTreeCurrent.append(newfulltree)
|
||||
|
||||
newtree[subgroup_operator] = newcurrent
|
||||
newfulltree[subgroup_operator] = newfulltreecurrent
|
||||
|
||||
self.current_operator = subgroup_operator
|
||||
self.queryTreeCurrent = newcurrent
|
||||
self.fullTreeCurrent = newfulltreecurrent
|
||||
|
||||
self.offset += Offset.SUBEXPRESSIONLENGTH
|
||||
self.again = True
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unknown field: %s" % (hex(self.criteria[self.offset]))
|
||||
logging.warning(errormessage)
|
||||
self.ignore += "Not processed: %s " % errormessage
|
||||
logging.debug(self.criteria[self.offset:self.offset + 100])
|
||||
|
||||
if not self.again:
|
||||
break
|
||||
|
||||
self.query = self._buildQuery(self._stripImplicitMediaKindFilter(self.root))
|
||||
self.output = self._buildOutputTree(self._stripImplicitMediaKindFilter(self.fullTreeRoot))
|
||||
|
||||
if self.info[Offset.LIMITBOOL] == 1:
|
||||
# Limit
|
||||
self.limit["number"] = self._iTunesUint(
|
||||
self.info[Offset.LIMITINT:Offset.LIMITINT + 4])
|
||||
|
||||
self.limit["type"] = LimitMethods(
|
||||
self.info[Offset.LIMITMETHOD]).name
|
||||
|
||||
# Selection
|
||||
selectionmethod = SelectionMethods(
|
||||
self.info[Offset.SELECTIONMETHOD]).name
|
||||
sign = int(self.info[Offset.SELECTIONMETHODSIGN] == 0)
|
||||
self.limit["order"] = SelectionMethodsStrings[selectionmethod][1] if isinstance(
|
||||
SelectionMethodsStrings[selectionmethod][1],
|
||||
str) else SelectionMethodsStrings[selectionmethod][1][sign]
|
||||
|
||||
if len(self.output) > 0:
|
||||
self.output += '\n'
|
||||
self.output += "Limited to %d %s selected by %s" % (self.limit["number"],
|
||||
self.limit["type"],
|
||||
SelectionMethodsStrings[selectionmethod][0] if isinstance(
|
||||
SelectionMethodsStrings[selectionmethod][0],
|
||||
str) else SelectionMethodsStrings[selectionmethod][0][sign])
|
||||
|
||||
if self.info[Offset.LIMITCHECKED] == 1:
|
||||
# Exclude unchecked items
|
||||
self.limit["onlychecked"] = True
|
||||
|
||||
if len(self.output) > 0:
|
||||
self.output += '\n'
|
||||
self.output += "Exclude unchecked items"
|
||||
else:
|
||||
self.limit["onlychecked"] = False
|
||||
|
||||
if self.info[Offset.LIVEUPDATE] == 0:
|
||||
# Live Update disabled
|
||||
self.limit["liveupdate"] = False
|
||||
|
||||
if len(self.output) > 0:
|
||||
self.output += '\n'
|
||||
self.output += "Live updating disabled"
|
||||
else:
|
||||
self.limit["liveupdate"] = True
|
||||
|
||||
t = self.limit
|
||||
t["tree"] = self.queryTree
|
||||
self.queryTree = t
|
||||
|
||||
t2 = self.limit
|
||||
t2["fulltree"] = self.fullTree
|
||||
self.fullTree = t2
|
||||
|
||||
self.is_parsed = True
|
||||
|
||||
def ProcessStringField(self):
|
||||
end = False
|
||||
self.fieldName = StringFields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "(lower(" + self.fieldName + ")"
|
||||
self.workingFull = {"field": self.fieldName, "type": "string"}
|
||||
|
||||
KindEval = None
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Contains:
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.StringPositive:
|
||||
self.workingOutput += " contains "
|
||||
self.workingQuery += " LIKE '%"
|
||||
self.workingFull["operator"] = "like"
|
||||
else:
|
||||
self.workingOutput += " does not contain "
|
||||
self.workingQuery += " NOT LIKE '%"
|
||||
self.workingFull["operator"] = "not like"
|
||||
if self.criteria[self.offset] == StringFields.Kind:
|
||||
KindEval = lambda kind, query: query.lower() in kind.name.lower()
|
||||
end = True
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.StringPositive:
|
||||
self.workingOutput += " is "
|
||||
self.workingQuery += " = '"
|
||||
self.workingFull["operator"] = "is"
|
||||
else:
|
||||
self.workingOutput += " is not "
|
||||
self.workingQuery += " != '"
|
||||
self.workingFull["operator"] = "is not"
|
||||
if self.criteria[self.offset] == StringFields.Kind:
|
||||
KindEval = lambda kind, query: query.lower() == kind.name.lower()
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Starts:
|
||||
self.workingOutput += " starts with "
|
||||
self.workingQuery += " Like '"
|
||||
self.workingFull["operator"] = "starts with"
|
||||
if self.criteria[self.offset] == StringFields.Kind:
|
||||
KindEval = lambda kind, query: kind.name.lower().startswith(query.lower())
|
||||
end = True
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Ends:
|
||||
self.workingOutput += " ends with "
|
||||
self.workingQuery += " Like '%"
|
||||
self.workingFull["operator"] = "ends with"
|
||||
if self.criteria[self.offset] == StringFields.Kind:
|
||||
KindEval = lambda kind, query: kind.name.lower().endswith(query.lower())
|
||||
end = True
|
||||
|
||||
self.workingOutput += '"'
|
||||
self.content = ""
|
||||
onByte = True
|
||||
for i in range(self.stringOffset, len(self.criteria)):
|
||||
if onByte:
|
||||
if self.criteria[i] == 0 and i != len(self.criteria) - 1:
|
||||
self.FinishStringField(end, KindEval)
|
||||
self.offset = i + 2
|
||||
self.again = True
|
||||
return
|
||||
self.content += chr(self.criteria[i])
|
||||
onByte = not onByte
|
||||
self.FinishStringField(end, KindEval)
|
||||
return
|
||||
|
||||
def _should_use_structured_kind_match(self, matched_kinds):
|
||||
if not matched_kinds:
|
||||
return False
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
return True
|
||||
|
||||
query = self.content.strip().lower()
|
||||
if len(query) < 3 or len(matched_kinds) > 3:
|
||||
return False
|
||||
|
||||
generic_tokens = {"audio", "video", "file", "movie", "protected", "purchased", "quicktime"}
|
||||
if query in generic_tokens:
|
||||
return False
|
||||
|
||||
query_pattern = re.compile(r"\b%s\b" % re.escape(query))
|
||||
return all(query_pattern.search(kind.name.lower()) for kind in matched_kinds)
|
||||
|
||||
def FinishStringField(self, end, KindEval):
|
||||
self.workingOutput += self.content
|
||||
self.workingOutput += '" '
|
||||
query_node = None
|
||||
if self.criteria[self.offset] == StringFields.Kind:
|
||||
self.workingFull["value"] = self.content
|
||||
matched_kinds = [kind for kind in FileKinds if KindEval(kind, self.content)]
|
||||
kindOperator = "like" if self.criteria[self.logicSignOffset] == LogicSign.StringPositive else "not like"
|
||||
if self._should_use_structured_kind_match(matched_kinds):
|
||||
kindNodes = []
|
||||
joiner = "or" if kindOperator == "like" else "and"
|
||||
for kind in matched_kinds:
|
||||
kindQuery = "(lower(Uri)"
|
||||
kindQuery += (" LIKE '%" +
|
||||
kind.extension +
|
||||
"')") if kindOperator == "like" else (" NOT LIKE '%" +
|
||||
kind.extension +
|
||||
"%')")
|
||||
kindNodes.append(("Kind", kindQuery))
|
||||
if len(kindNodes) == 1:
|
||||
query_node = kindNodes[0]
|
||||
else:
|
||||
query_node = {joiner: kindNodes}
|
||||
else:
|
||||
logging.warning(
|
||||
'Treating Kind rule as free text instead of structured file-kind match: %s %s "%s"',
|
||||
self.fieldName,
|
||||
self.workingFull["operator"],
|
||||
self.content,
|
||||
)
|
||||
self.workingQuery += self.content.lower()
|
||||
self.workingQuery += "%')" if end else "')"
|
||||
query_node = (self.fieldName, self.workingQuery)
|
||||
else:
|
||||
self.workingQuery += self.content.lower()
|
||||
self.workingQuery += "%')" if end else "')"
|
||||
self.workingFull["value"] = self.content
|
||||
query_node = (self.fieldName, self.workingQuery)
|
||||
|
||||
if len(self.ignore) > 0:
|
||||
self.ignore += " or\n" if self.current_operator == "or" else " and\n"
|
||||
|
||||
self.queryTreeCurrent.append(query_node)
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
def ProcessIntField(self):
|
||||
self.fieldName = IntFields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "(" + self.fieldName
|
||||
self.workingFull = {"field": self.fieldName, "type": "int"}
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
number = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is %d" % number
|
||||
self.workingQuery += " = %d" % number
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = number
|
||||
else:
|
||||
self.workingOutput += " is not %d" % number
|
||||
self.workingQuery += " != %d" % number
|
||||
self.workingFull["operator"] = "is not"
|
||||
self.workingFull["value"] = number
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Greater:
|
||||
number = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
self.workingOutput += " is greater than %d" % number
|
||||
self.workingQuery += " > %d" % number
|
||||
self.workingFull["operator"] = "greater than"
|
||||
self.workingFull["value"] = number
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Less:
|
||||
number = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
self.workingOutput += " is less than %d" % number
|
||||
self.workingQuery += " < %d" % number
|
||||
self.workingFull["operator"] = "less than"
|
||||
self.workingFull["value"] = number
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Other:
|
||||
if self.criteria[self.logicSignOffset + 2] == 1:
|
||||
numberA = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
numberB = self._iTunesUint(
|
||||
self.criteria[self.intBOffset:self.intBOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
self.workingOutput += " is in the range of %d to %d" % (
|
||||
numberA, numberB)
|
||||
self.workingQuery += " BETWEEN %d AND %d" % (numberA, numberB)
|
||||
self.workingFull["operator"] = "between"
|
||||
self.workingFull["value"] = (numberA, numberB)
|
||||
|
||||
else:
|
||||
numberA = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
numberB = self._iTunesUint(
|
||||
self.criteria[self.intBOffset:self.intBOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
if numberA == numberB:
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is %d" % numberA
|
||||
self.workingQuery += " = %d" % numberA
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = numberA
|
||||
else:
|
||||
self.workingOutput += " is not %d" % numberA
|
||||
self.workingQuery += " != %d" % numberA
|
||||
self.workingFull["operator"] = "is not"
|
||||
self.workingFull["value"] = numberA
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unkown case in ProcessIntField:LogicRule.Other: a=%d and b=%d" % (numberA, numberB)
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
|
||||
self.workingOutput += " ##UnkownCase IntField: LogicRule.Other##"
|
||||
self.workingQuery += " ##UnkownCase IntField: LogicRule.Other##"
|
||||
|
||||
self.workingQuery += ")"
|
||||
|
||||
self.queryTreeCurrent.append((self.fieldName, self.workingQuery))
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
self.offset = self.intAOffset + Offset.INTLENGTH
|
||||
if len(self.criteria) > self.offset:
|
||||
self.again = True
|
||||
|
||||
def ProcessPlaylistField(self):
|
||||
self.fieldName = PlaylistFields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "(" + self.fieldName
|
||||
self.workingFull = {"field": self.fieldName, "type": "playlist"}
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
idpart0 = self._iTunesUint(
|
||||
self.criteria[self.intAOffset - 4:self.intAOffset], self.criteria[self.offset] == IntFields.Rating)
|
||||
idpart1 = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is %s" % self._formatPersistentID(idpart0, idpart1)
|
||||
self.workingQuery += " = '%s'" % self._formatPersistentID(idpart0, idpart1)
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = "%s" % self._formatPersistentID(idpart0, idpart1)
|
||||
else:
|
||||
self.workingOutput += " is not %s" % self._formatPersistentID(idpart0, idpart1)
|
||||
self.workingQuery += " != '%s'" % self._formatPersistentID(idpart0, idpart1)
|
||||
self.workingFull["operator"] = "is not"
|
||||
self.workingFull["value"] = "%s" % self._formatPersistentID(idpart0, idpart1)
|
||||
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unkown logic rule in ProcessPlaylistField: LogicRule=%d" % self.criteria[self.logicRulesOffset]
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
self.workingOutput += " ##UnkownCase PlaylistField:LogicRule##"
|
||||
self.workingQuery += " ##UnkownCase PlaylistField:LogicRule##"
|
||||
|
||||
self.workingQuery += ")"
|
||||
|
||||
self.queryTreeCurrent.append((self.fieldName, self.workingQuery))
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
self.offset = self.intAOffset + Offset.INTLENGTH
|
||||
if len(self.criteria) > self.offset:
|
||||
self.again = True
|
||||
|
||||
def ProcessBooleanField(self):
|
||||
self.fieldName = BooleanFields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "(" + self.fieldName
|
||||
self.workingFull = {"field": self.fieldName, "type": "boolean"}
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
value = self.criteria[self.logicSignOffset] != LogicSign.IntPositive
|
||||
boolstr = "True" if value == 1 else "False"
|
||||
|
||||
self.workingOutput += " is %s" % (boolstr)
|
||||
self.workingQuery += " = %d" % (value)
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = value == 1
|
||||
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unkown logic rule in ProcessBooleanField: LogicRule=%d" % self.criteria[self.logicRulesOffset]
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
self.workingOutput += " ##UnkownCase BooleanField:LogicRule##"
|
||||
self.workingQuery += " ##UnkownCase BooleanField:LogicRule##"
|
||||
|
||||
self.workingQuery += ")"
|
||||
|
||||
self.queryTreeCurrent.append((self.fieldName, self.workingQuery))
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
self.offset = self.intAOffset + Offset.INTLENGTH
|
||||
if len(self.criteria) > self.offset:
|
||||
self.again = True
|
||||
|
||||
def ProcessDateField(self):
|
||||
self.fieldName = DateFields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "TIMESTAMP(%s)" % self.fieldName
|
||||
self.workingFull = {"field": self.fieldName, "type": "date"}
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Greater:
|
||||
timestamp = self._iTunesDate(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4])
|
||||
self.workingOutput += " is after %s" % self._dateString(timestamp)
|
||||
self.workingQuery += " > %d" % timestamp
|
||||
self.workingFull["operator"] = "is after"
|
||||
self.workingFull["value"] = timestamp
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Less:
|
||||
timestamp = self._iTunesDate(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4])
|
||||
self.workingOutput += " is before %s" % self._dateString(timestamp)
|
||||
self.workingQuery += " < %d" % timestamp
|
||||
self.workingFull["operator"] = "is before"
|
||||
self.workingFull["value"] = timestamp
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Other:
|
||||
if self.criteria[self.logicSignOffset + 2] == 1:
|
||||
timestampA = self._iTunesDate(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4])
|
||||
timestampB = self._iTunesDate(
|
||||
self.criteria[self.intBOffset:self.intBOffset + 4])
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is in the range of %s to %s" % (
|
||||
self._dateString(timestampA), self._dateString(timestampB))
|
||||
self.workingQuery += " BETWEEN %d AND %d" % (
|
||||
timestampA, timestampB)
|
||||
self.workingFull["operator"] = "is in the range"
|
||||
self.workingFull["value"] = (timestampA, timestampB)
|
||||
self.workingFull["value_date"] = (
|
||||
self._dateString(timestampA), self._dateString(timestampB))
|
||||
else:
|
||||
self.workingOutput += " is not in the range of %s to %s" % (
|
||||
self._dateString(timestampA), self._dateString(timestampB))
|
||||
self.workingQuery += " NOT BETWEEN %d AND %d" % (
|
||||
timestampA, timestampB)
|
||||
self.workingFull["operator"] = "is not in the range"
|
||||
self.workingFull["value"] = (timestampA, timestampB)
|
||||
self.workingFull["value_date"] = (
|
||||
self._dateString(timestampA), self._dateString(timestampB))
|
||||
elif self.criteria[self.logicSignOffset + 2] == 2:
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is in the last "
|
||||
self.workingQuery = "(TIMESTAMP(NOW()) - TIMESTAMP(%s)) < " % self.fieldName
|
||||
self.workingFull["operator"] = "is in the last"
|
||||
else:
|
||||
self.workingOutput += " is not in the last "
|
||||
self.workingQuery = "(TIMESTAMP(NOW()) - TIMESTAMP(%s)) > " % self.fieldName
|
||||
self.workingFull["operator"] = "is not in the last"
|
||||
|
||||
t = (self._iTunesUint(bytes(
|
||||
[255 - c for c in self.criteria[self.timeValueOffset:self.timeValueOffset + 4]])) + 1) % 4294967296
|
||||
multiple = self._iTunesUint(
|
||||
self.criteria[self.timeMultipleOffset:self.timeMultipleOffset + 4])
|
||||
self.workingQuery += "%d" % (t * multiple)
|
||||
self.workingFull["value"] = t * multiple
|
||||
if multiple == 86400:
|
||||
self.workingOutput += "%d days" % t
|
||||
self.workingFull["value_date"] = "%d days" % t
|
||||
elif multiple == 604800:
|
||||
self.workingOutput += "%d weeks" % t
|
||||
self.workingFull["value_date"] = "%d weeks" % t
|
||||
elif multiple == 2628000:
|
||||
self.workingOutput += "%d months" % t
|
||||
self.workingFull["value_date"] = "%d months" % t
|
||||
else: # pragma: no cover
|
||||
self.workingOutput += "%d*%d seconds" % (multiple, t)
|
||||
self.workingFull["value_date"] = "%d*%d seconds" % (
|
||||
multiple, t)
|
||||
errormessage = "##UnkownCase DateField: LogicRule.Other: multiple '%d' is unkown##" % multiple
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
|
||||
self.queryTreeCurrent.append((self.fieldName, self.workingQuery))
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
self.offset = self.intAOffset + Offset.INTLENGTH
|
||||
if len(self.criteria) > self.offset:
|
||||
self.again = True
|
||||
|
||||
def ProcessListField(self, fields, valueDict, listtype="list"):
|
||||
self.fieldName = fields(self.criteria[self.offset]).name
|
||||
self.workingOutput = self.fieldName
|
||||
self.workingQuery = "(" + self.fieldName
|
||||
self.workingFull = {"field": self.fieldName, "type": listtype}
|
||||
|
||||
if self.criteria[self.logicRulesOffset] == LogicRule.Is:
|
||||
number = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
value = self._lookupListValue(valueDict, number, self.fieldName, listtype)
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is %s" % value
|
||||
self.workingQuery += " = '%s'" % value
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = value
|
||||
|
||||
else:
|
||||
self.workingOutput += " is not %s" % value
|
||||
self.workingQuery += " != '%s'" % value
|
||||
self.workingFull["operator"] = "is not"
|
||||
self.workingFull["value"] = value
|
||||
|
||||
elif self.criteria[self.logicRulesOffset] == LogicRule.Other:
|
||||
numberA = self._iTunesUint(
|
||||
self.criteria[self.intAOffset:self.intAOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
numberB = self._iTunesUint(
|
||||
self.criteria[self.intBOffset:self.intBOffset + 4], self.criteria[self.offset] == IntFields.Rating)
|
||||
if numberA == numberB:
|
||||
value = self._lookupListValue(valueDict, numberA, self.fieldName, listtype)
|
||||
if self.criteria[self.logicSignOffset] == LogicSign.IntPositive:
|
||||
self.workingOutput += " is %s" % value
|
||||
self.workingQuery += " = '%s'" % value
|
||||
self.workingFull["operator"] = "is"
|
||||
self.workingFull["value"] = value
|
||||
else:
|
||||
self.workingOutput += " is not %s" % value
|
||||
self.workingQuery += " != '%s'" % value
|
||||
self.workingFull["operator"] = "is not"
|
||||
self.workingFull["value"] = value
|
||||
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unkown case in ProcessListField %s:LogicRule.Other: %d != %d" % (self.fieldName, numberA, numberB)
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
|
||||
self.workingOutput += " ##UnkownCase ListField %s: LogicRule.Other##" % self.fieldName
|
||||
self.workingQuery += " ##UnkownCase ListField %s: LogicRule.Other##" % self.fieldName
|
||||
else: # pragma: no cover
|
||||
errormessage = "Unkown logic rule in ProcessListField %s: LogicRule=%d" % (self.fieldName, self.criteria[self.logicRulesOffset])
|
||||
logging.warning(errormessage)
|
||||
self.ignore += " Not processed: %s " % errormessage
|
||||
|
||||
self.workingOutput += " ##UnkownCase ListField %s:LogicRule##" % self.fieldName
|
||||
self.workingQuery += " ##UnkownCase ListField %s:LogicRule##" % self.fieldName
|
||||
|
||||
self.workingQuery += ")"
|
||||
|
||||
self.queryTreeCurrent.append((self.fieldName, self.workingQuery))
|
||||
self.fullTreeCurrent.append(self.workingFull)
|
||||
|
||||
self.offset = self.intAOffset + Offset.INTLENGTH
|
||||
if len(self.criteria) > self.offset:
|
||||
self.again = True
|
||||
|
||||
@staticmethod
|
||||
def _iTunesUint(bytearr, divideby=False, denominator=20):
|
||||
num = struct.unpack('>I', bytearr)[0]
|
||||
if divideby: # For rating/stars by 20
|
||||
num = int(num / denominator)
|
||||
return num
|
||||
|
||||
@classmethod
|
||||
def _iTunesDate(cls, bytearr):
|
||||
timestamp = cls._iTunesUint(bytearr)
|
||||
return timestamp + DateStartFromUnix
|
||||
|
||||
@staticmethod
|
||||
def _dateString(timestamp):
|
||||
if sys.version_info < (3, 11):
|
||||
return datetime.datetime.utcfromtimestamp(
|
||||
int(timestamp)).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
return datetime.datetime.fromtimestamp(
|
||||
int(timestamp), datetime.UTC).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
@staticmethod
|
||||
def _formatPersistentID(idpart0, idpart1):
|
||||
return '{:08X}{:08X}'.format(idpart0, idpart1)
|
||||
|
||||
@staticmethod
|
||||
def _operatorFromLogicType(logictype):
|
||||
if logictype == 1:
|
||||
return "or"
|
||||
if logictype == 0:
|
||||
return "and"
|
||||
|
||||
logging.error("Unknown logic type encountered: %d; defaulting to 'and'", logictype)
|
||||
return "and"
|
||||
|
||||
@staticmethod
|
||||
def _lookupListValue(valueDict, number, fieldName="unknown", listtype="list"):
|
||||
if number in valueDict:
|
||||
return valueDict[number]
|
||||
logging.warning("Unknown %s list value encountered for %s: %d", listtype, fieldName, number)
|
||||
return "UnknownValue[%d]" % number
|
||||
|
||||
def _buildQuery(self, node, nested=False):
|
||||
if not node:
|
||||
return ""
|
||||
|
||||
if isinstance(node, tuple):
|
||||
return node[1]
|
||||
|
||||
if isinstance(node, dict):
|
||||
if "and" in node:
|
||||
rendered = " AND ".join(
|
||||
filter(None, (self._buildQuery(child, nested=True) for child in node["and"]))
|
||||
)
|
||||
elif "or" in node:
|
||||
rendered = " OR ".join(
|
||||
filter(None, (self._buildQuery(child, nested=True) for child in node["or"]))
|
||||
)
|
||||
else:
|
||||
return ""
|
||||
if not rendered:
|
||||
return ""
|
||||
if nested:
|
||||
return "( %s )" % rendered
|
||||
return rendered
|
||||
|
||||
return ""
|
||||
|
||||
def _stripImplicitMediaKindFilter(self, node):
|
||||
if not isinstance(node, dict) or "and" not in node:
|
||||
return node
|
||||
|
||||
children = list(node["and"])
|
||||
if len(children) < 2 or not self._isImplicitMediaKindFilter(children[0]):
|
||||
return node
|
||||
|
||||
remaining = children[1:]
|
||||
if len(remaining) == 1:
|
||||
return remaining[0]
|
||||
return {"and": remaining}
|
||||
|
||||
@staticmethod
|
||||
def _isImplicitMediaKindFilter(node):
|
||||
if isinstance(node, tuple):
|
||||
return node[0] == "MediaKind" and node[1] in {
|
||||
"(MediaKind = 'Music')",
|
||||
"(MediaKind = 'Music Video')",
|
||||
}
|
||||
|
||||
if isinstance(node, dict) and "or" not in node:
|
||||
return (
|
||||
node.get("field") == "MediaKind" and
|
||||
node.get("operator") == "is" and
|
||||
node.get("value") in {"Music", "Music Video"}
|
||||
)
|
||||
|
||||
if not isinstance(node, dict) or "or" not in node:
|
||||
return False
|
||||
|
||||
values = []
|
||||
for child in node["or"]:
|
||||
if isinstance(child, tuple):
|
||||
if child[0] != "MediaKind":
|
||||
return False
|
||||
if child[1] == "(MediaKind = 'Music')":
|
||||
values.append("Music")
|
||||
elif child[1] == "(MediaKind = 'Music Video')":
|
||||
values.append("Music Video")
|
||||
else:
|
||||
return False
|
||||
elif isinstance(child, dict):
|
||||
if child.get("field") != "MediaKind" or child.get("operator") != "is":
|
||||
return False
|
||||
if child.get("value") not in {"Music", "Music Video"}:
|
||||
return False
|
||||
values.append(child["value"])
|
||||
else:
|
||||
return False
|
||||
|
||||
return sorted(values) == ["Music", "Music Video"]
|
||||
|
||||
def _buildOutputTree(self, node, nested=False):
|
||||
if not node:
|
||||
return ""
|
||||
|
||||
if isinstance(node, dict):
|
||||
if "and" in node:
|
||||
rendered = ' and\n'.join(
|
||||
filter(None, (self._buildOutputTree(child, nested=True) for child in node["and"]))
|
||||
)
|
||||
return self._formatNestedOutput(rendered) if nested else rendered
|
||||
if "or" in node:
|
||||
rendered = ' or\n'.join(
|
||||
filter(None, (self._buildOutputTree(child, nested=True) for child in node["or"]))
|
||||
)
|
||||
return self._formatNestedOutput(rendered) if nested else rendered
|
||||
return self._renderOutputLeaf(node)
|
||||
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _formatNestedOutput(rendered):
|
||||
if not rendered:
|
||||
return ""
|
||||
return "[\n\t%s\n]" % "\n\t".join(rendered.split("\n"))
|
||||
|
||||
def _renderOutputLeaf(self, node):
|
||||
field = node["field"]
|
||||
operator = node["operator"]
|
||||
value = node.get("value_date", node.get("value"))
|
||||
|
||||
if node["type"] == "string":
|
||||
if operator == "like":
|
||||
return '%s contains "%s" ' % (field, value)
|
||||
if operator == "not like":
|
||||
return '%s does not contain "%s" ' % (field, value)
|
||||
if operator == "is":
|
||||
return '%s is "%s" ' % (field, value)
|
||||
if operator == "is not":
|
||||
return '%s is not "%s" ' % (field, value)
|
||||
if operator == "starts with":
|
||||
return '%s starts with "%s" ' % (field, value)
|
||||
if operator == "ends with":
|
||||
return '%s ends with "%s" ' % (field, value)
|
||||
|
||||
if operator == "is":
|
||||
return "%s is %s" % (field, value)
|
||||
|
||||
if operator == "is not":
|
||||
return "%s is not %s" % (field, value)
|
||||
|
||||
if operator in {"is in the range", "is not in the range"} and isinstance(value, tuple):
|
||||
return "%s %s of %s to %s" % (field, operator, value[0], value[1])
|
||||
|
||||
if operator == "greater than":
|
||||
return "%s is greater than %s" % (field, value)
|
||||
|
||||
if operator == "less than":
|
||||
return "%s is less than %s" % (field, value)
|
||||
|
||||
if operator == "is after":
|
||||
return "%s is after %s" % (field, value)
|
||||
|
||||
if operator == "is before":
|
||||
return "%s is before %s" % (field, value)
|
||||
|
||||
if operator == "is in the last":
|
||||
return "%s is in the last %s" % (field, value)
|
||||
|
||||
if operator == "is not in the last":
|
||||
return "%s is not in the last %s" % (field, value)
|
||||
|
||||
if operator == "between" and isinstance(value, tuple):
|
||||
return "%s is in the range of %s to %s" % (field, value[0], value[1])
|
||||
|
||||
if operator == "not between" and isinstance(value, tuple):
|
||||
return "%s is not in the range of %s to %s" % (field, value[0], value[1])
|
||||
|
||||
return "%s %s %s" % (field, operator, value)
|
||||
Reference in New Issue
Block a user