#!/usr/bin/env python3
"""
autopatch_kodi.py - Watched & Watchlist Indicator Bridge for POV, Arctic Fuse 3 & TMDb Helper
Overview for addon/skin developers (e.g. POV):
- watchlist_rank: Originates from TMDb Helper as a 1-based numeric rank/position of an item
on the user's watchlist (not a service ID like 1=MDbList, 2=Trakt). Arctic Fuse 3 checks
`!String.IsEmpty(ListItem.Property(watchlist_rank))` to show its native watchlist badge,
so setting any non-empty string (such as '1' or the 1-based list index) enables native
watchlist indicators in AF3 without requiring skin changes.
- Extras & People dialogs: Since POV's `extras.xml` and `people.xml` are custom addon windows,
they use POV's own ListItem properties (`tikiskins.extras.watched` / `.watchlist` and
`tikiskins.person.watched` / `.watchlist`) rather than skin-wide indicators.
"""
import os, re, shutil, datetime
LOG = "/storage/.kodi/temp/autopatch.log"
POV = "/storage/.kodi/addons/plugin.video.pov"
AF3 = "/storage/.kodi/addons/skin.arctic.fuse.3"
TMDBH = "/storage/.kodi/addons/plugin.video.themoviedb.helper"
changes = []
def read(p):
with open(p, "r", encoding="utf-8") as f:
return f.read()
def write(p, content, label):
with open(p, "w", encoding="utf-8") as f:
f.write(content)
changes.append(label)
# 2. POV: Copy Arctic Fuse icons if missing after update
for src_name, dst_name in [("circle-check.png", "af_watched.png"), ("watchlist.png", "af_watchlist.png")]:
src = f"{AF3}/extras/icons/{src_name}"
dst = f"{POV}/resources/skins/Default/media/{dst_name}"
if os.path.exists(src) and not os.path.exists(dst):
shutil.copy2(src, dst)
changes.append(f"POV media/{dst_name} restored")
# 3. POV: extras.py (watched + watchlist)
p_ext_py = f"{POV}/resources/lib/windows/extras.py"
if os.path.exists(p_ext_py):
txt = read(p_ext_py)
if "tikiskins.extras.watchlist" not in txt:
if "mdblist_api" not in txt:
txt = txt.replace("from caches import watched_cache as ws", "from caches import watched_cache as ws\nfrom indexers import mdblist_api", 1)
old = """\t\tname_key = 'title' if self.is_movie else 'name'
\t\trelease_key = 'release_date' if self.is_movie else 'first_air_date'
\t\titem_list = []
\t\tfor item in data:
\t\t\ttry:
\t\t\t\tposter_path = item['poster_path']
\t\t\t\tif poster_path: thumbnail = tmdb_image_base % (self.poster_resolution, poster_path)
\t\t\t\telse: thumbnail = poster_empty
\t\t\t\tyear = self.get_release_year(item[release_key])
\t\t\t\tlistitem = self.make_listitem()
\t\t\t\tlistitem.setProperty('tikiskins.extras.name', item[name_key])
\t\t\t\tlistitem.setProperty('tikiskins.extras.release_date', year)
\t\t\t\tlistitem.setProperty('tikiskins.extras.vote_average', '%.1f' % item['vote_average'])
\t\t\t\tlistitem.setProperty('tikiskins.extras.thumbnail', thumbnail)
\t\t\t\tlistitem.setProperty('tikiskins.extras.tmdb_id', str(item['id']))
\t\t\t\titem_list.append(listitem)"""
new = """\t\tname_key = 'title' if self.is_movie else 'name'
\t\trelease_key = 'release_date' if self.is_movie else 'first_air_date'
\t\twatched_info = ws.get_watched_info_movie(self.watched_indicators) if self.is_movie else {}
\t\ttry: watchlist_ids = {str(i['id']) for i in mdblist_api.mdbl_collection_watchlist_items('watchlist', 'movie' if self.is_movie else 'tv')}
\t\texcept: watchlist_ids = set()
\t\titem_list = []
\t\tfor item in data:
\t\t\ttry:
\t\t\t\tposter_path = item['poster_path']
\t\t\t\tif poster_path: thumbnail = tmdb_image_base % (self.poster_resolution, poster_path)
\t\t\t\telse: thumbnail = poster_empty
\t\t\t\tyear = self.get_release_year(item[release_key])
\t\t\t\tplaycount = ws.get_watched_status_movie(watched_info, str(item['id']))[0] if self.is_movie else 0
\t\t\t\tlistitem = self.make_listitem()
\t\t\t\tlistitem.setProperty('tikiskins.extras.name', item[name_key])
\t\t\t\tlistitem.setProperty('tikiskins.extras.release_date', year)
\t\t\t\tlistitem.setProperty('tikiskins.extras.vote_average', '%.1f' % item['vote_average'])
\t\t\t\tlistitem.setProperty('tikiskins.extras.thumbnail', thumbnail)
\t\t\t\tlistitem.setProperty('tikiskins.extras.tmdb_id', str(item['id']))
\t\t\t\tlistitem.setProperty('tikiskins.extras.watched', 'true' if playcount == 1 else 'false')
\t\t\t\tlistitem.setProperty('tikiskins.extras.watchlist', 'true' if str(item['id']) in watchlist_ids else 'false')
\t\t\t\titem_list.append(listitem)"""
if old in txt:
write(p_ext_py, txt.replace(old, new, 1), "POV extras.py")
# 4. POV: people.py (watched + watchlist)
p_ppl_py = f"{POV}/resources/lib/windows/people.py"
if os.path.exists(p_ppl_py):
txt = read(p_ppl_py)
if "tikiskins.person.watchlist" not in txt:
if "watched_cache as ws" not in txt:
txt = txt.replace("from indexers import metadata, tmdb_api", "from caches import watched_cache as ws\nfrom indexers import metadata, tmdb_api, mdblist_api", 1)
if "watched_indicators" not in txt:
txt = txt.replace("from modules.settings import extras_enable_scrollbars", "from modules.settings import watched_indicators, extras_enable_scrollbars", 1)
old = """\t\tname_key = 'title' if mediatype == 'movie' else 'name'
\t\trelease_key = 'release_date' if mediatype == 'movie' else 'first_air_date'
\t\tfor item in sorted(data, key=lambda x: x.get(release_key) or '', reverse=True):
\t\t\ttry:
\t\t\t\ttmdb_id = item['id']
\t\t\t\tif tmdb_id in used_ids: continue
\t\t\t\tlistitem = self.make_listitem()
\t\t\t\tposter_path = item['poster_path']
\t\t\t\tif not poster_path: thumbnail = backup_thumbnail
\t\t\t\telse: thumbnail = tmdb_api.tmdb_image_base % (self.poster_resolution, poster_path)
\t\t\t\tyear = item.get(release_key)
\t\t\t\tif year not in (None, ''):
\t\t\t\t\ttry: year = year.split('-')[0]
\t\t\t\t\texcept: pass
\t\t\t\telse: year = 'N/A'
\t\t\t\tlistitem.setProperty('tikiskins.person.name', item[name_key])
\t\t\t\tlistitem.setProperty('tikiskins.person.release_date', year)
\t\t\t\tlistitem.setProperty('tikiskins.person.vote_average', '%.1f' % item['vote_average'])
\t\t\t\tlistitem.setProperty('tikiskins.person.thumbnail', thumbnail)
\t\t\t\tlistitem.setProperty('tikiskins.person.tmdb_id', str(tmdb_id))
\t\t\t\tused_ids_append(tmdb_id)
\t\t\t\tyield listitem"""
new = """\t\tname_key = 'title' if mediatype == 'movie' else 'name'
\t\trelease_key = 'release_date' if mediatype == 'movie' else 'first_air_date'
\t\tw_ind = watched_indicators()
\t\twatched_info = ws.get_watched_info_movie(w_ind) if mediatype == 'movie' else {}
\t\ttry: watchlist_ids = {str(i['id']) for i in mdblist_api.mdbl_collection_watchlist_items('watchlist', mediatype)}
\t\texcept: watchlist_ids = set()
\t\tfor item in sorted(data, key=lambda x: x.get(release_key) or '', reverse=True):
\t\t\ttry:
\t\t\t\ttmdb_id = item['id']
\t\t\t\tif tmdb_id in used_ids: continue
\t\t\t\tplaycount = ws.get_watched_status_movie(watched_info, str(tmdb_id))[0] if mediatype == 'movie' else 0
\t\t\t\tlistitem = self.make_listitem()
\t\t\t\tposter_path = item['poster_path']
\t\t\t\tif not poster_path: thumbnail = backup_thumbnail
\t\t\t\telse: thumbnail = tmdb_api.tmdb_image_base % (self.poster_resolution, poster_path)
\t\t\t\tyear = item.get(release_key)
\t\t\t\tif year not in (None, ''):
\t\t\t\t\ttry: year = year.split('-')[0]
\t\t\t\t\texcept: pass
\t\t\t\telse: year = 'N/A'
\t\t\t\tlistitem.setProperty('tikiskins.person.name', item[name_key])
\t\t\t\tlistitem.setProperty('tikiskins.person.release_date', year)
\t\t\t\tlistitem.setProperty('tikiskins.person.vote_average', '%.1f' % item['vote_average'])
\t\t\t\tlistitem.setProperty('tikiskins.person.thumbnail', thumbnail)
\t\t\t\tlistitem.setProperty('tikiskins.person.tmdb_id', str(tmdb_id))
\t\t\t\tlistitem.setProperty('tikiskins.person.watched', 'true' if playcount == 1 else 'false')
\t\t\t\tlistitem.setProperty('tikiskins.person.watchlist', 'true' if str(tmdb_id) in watchlist_ids else 'false')
\t\t\t\tused_ids_append(tmdb_id)
\t\t\t\tyield listitem"""
if old in txt:
write(p_ppl_py, txt.replace(old, new, 1), "POV people.py")
# 5. POV: extras.xml & people.xml (badges)
for xml_name, w_prop, wl_prop in [
("extras.xml", "tikiskins.extras.watched", "tikiskins.extras.watchlist"),
("people.xml", "tikiskins.person.watched", "tikiskins.person.watchlist")
]:
p_xml = f"{POV}/resources/skins/Default/1080i/{xml_name}"
if os.path.exists(p_xml):
txt = read(p_xml)
if "af_watched.png" not in txt:
thumb_prop = w_prop.replace(".watched", ".thumbnail")
pat = re.compile(r'(\s*\$INFO\[ListItem\.Property\(' + re.escape(thumb_prop) + r'\)\]\s*)')
repl = (
r'\1\n'
f' \n'
f' 189\n'
f' 13\n'
f' 34\n'
f' 34\n'
f' af_watched.png\n'
f' String.IsEqual(ListItem.Property({w_prop}),true)\n'
f' \n'
f' \n'
f' 13\n'
f' 13\n'
f' 34\n'
f' 34\n'
f' af_watchlist.png\n'
f' String.IsEqual(ListItem.Property({wl_prop}),true)\n'
f' '
)
txt_new, cnt = pat.subn(repl, txt)
if cnt > 0:
write(p_xml, txt_new, f"POV {xml_name}")
# 6. POV: movies.py & tvshows.py (watchlist_rank initialized once in __init__)
p_mov = f"{POV}/resources/lib/menus/movies.py"
if os.path.exists(p_mov):
txt = read(p_mov)
if "_mdbl_wl" not in txt:
if "from indexers import mdblist_api" not in txt:
txt = "from indexers import mdblist_api\n" + txt
init_pat = re.compile(r'(def __init__\(self[^\n]*\):\n)')
init_repl = r'\1\t\ttry: self._mdbl_wl = {str(i[\'id\']) for i in mdblist_api.mdbl_collection_watchlist_items(\'watchlist\', \'movie\')}\n\t\texcept: self._mdbl_wl = set()\n'
old = "\t\t\tprops = {'pov_sort_order': string(position), 'watchedprogress': progress}"
new = old + "\n\t\t\tif str(tmdb_id) in self._mdbl_wl: props['watchlist_rank'] = '1'"
if init_pat.search(txt) and old in txt:
txt = init_pat.sub(init_repl, txt, count=1).replace(old, new, 1)
write(p_mov, txt, "POV movies.py")
p_tv = f"{POV}/resources/lib/menus/tvshows.py"
if os.path.exists(p_tv):
txt = read(p_tv)
if "_mdbl_wl" not in txt:
if "from indexers import mdblist_api" not in txt:
txt = "from indexers import mdblist_api\n" + txt
init_pat = re.compile(r'(def __init__\(self[^\n]*\):\n)')
init_repl = r'\1\t\ttry: self._mdbl_wl = {str(i[\'id\']) for i in mdblist_api.mdbl_collection_watchlist_items(\'watchlist\', \'tv\')}\n\t\texcept: self._mdbl_wl = set()\n'
old = """\t\t\tprops = {
\t\t\t\t'pov_sort_order': string(position), 'unwatchedepisodes': string(total_unwatched),
\t\t\t\t'totalseasons': string(total_seasons), 'totalepisodes': string(total_aired_eps),
\t\t\t\t'watchedepisodes': string(total_watched), 'watchedprogress': string(int(watchedprogress))
\t\t\t}"""
new = old + "\n\t\t\tif str(tmdb_id) in self._mdbl_wl: props['watchlist_rank'] = '1'"
if init_pat.search(txt) and old in txt:
txt = init_pat.sub(init_repl, txt, count=1).replace(old, new, 1)
write(p_tv, txt, "POV tvshows.py")
# 7. Arctic Fuse 3: Blue watchlist icon in Includes_Objects.xml
p_obj = f"{AF3}/1080i/Includes_Objects.xml"
if os.path.exists(p_obj):
txt = read(p_obj)
old = 'special://skin/extras/icons/circle-plus.png'
new = 'special://skin/extras/icons/bookmark.png'
if old in txt:
write(p_obj, txt.replace(old, new, 1), "AF3 Includes_Objects.xml")
# 8. Arctic Fuse 3: Disable sync_watchedon in Includes_Settings.xml
p_set = f"{AF3}/1080i/Includes_Settings.xml"
if os.path.exists(p_set):
txt = read(p_set)
lines = txt.splitlines()
patched = False
for idx, line in enumerate(lines):
if "sync_watchedon" in line and ""
patched = True
if patched:
write(p_set, "\n".join(lines) + "\n", "AF3 Includes_Settings.xml (sync_watchedon)")
# 8b. Arctic Fuse 3: Green (watched), blue (watchlist), red (unwatched) in list view
p_img = f"{AF3}/1080i/Includes_Images.xml"
if os.path.exists(p_img):
txt = read(p_img)
if "Color_Overlay_List" not in txt:
old_var = """
indicator/play.png
indicator/checkmark-fo.png
indicator/library.png
indicator/movieset.png
indicator/folder.png
indicator/library.png
indicator/dot.png
"""
new_var = """
FF00E676
FF00B0FF
FFFF5252
main_fg_100
indicator/play.png
special://skin/extras/icons/circle-check.png
special://skin/extras/icons/circle-plus.png
indicator/library.png
indicator/movieset.png
indicator/folder.png
indicator/library.png
special://skin/extras/icons/circle-xmark.png
indicator/dot.png
"""
if old_var in txt:
write(p_img, txt.replace(old_var, new_var, 1), "AF3 Includes_Images.xml (green/blue/red overlay)")
if os.path.exists(p_obj):
txt = read(p_obj)
old_ctrl = """ $VAR[ColorSelected]
main_fg_100
$VAR[Image_Overlay_List]"""
new_ctrl = """ $VAR[Color_Overlay_List]
$VAR[Image_Overlay_List]"""
if old_ctrl in txt:
write(p_obj, txt.replace(old_ctrl, new_ctrl, 1), "AF3 Includes_Objects.xml (Color_Overlay_List)")
if os.path.exists(p_obj):
txt = read(p_obj)
ov = '[$PARAM[playing]] | [$PARAM[episodes]] | [$PARAM[timers]] | [$PARAM[progress]] | [$PARAM[watched]] | [$PARAM[library]] | [$PARAM[collection]]'
nv = '[$PARAM[playing]] | [$PARAM[episodes]] | [$PARAM[timers]] | [$PARAM[progress]] | [$PARAM[watched]] | [$PARAM[library]] | [$PARAM[collection]] | !String.IsEmpty(ListItem.Property(watchlist_rank))'
if ov in txt and 'watchlist_rank))' not in txt:
write(p_obj, txt.replace(ov, nv, 1), "AF3 Includes_Objects.xml (Object_Indicator_Visible watchlist)")
if os.path.exists(p_obj):
txt = read(p_obj)
if "Skin.HasSetting(Indicator.TraktWatchlist)" in txt:
t2 = txt.replace("Skin.HasSetting(Indicator.TraktWatchlist)\n", "")
t2 = t2.replace("special://skin/extras/icons/watchlist.png", "special://skin/extras/icons/bookmark.png")
write(p_obj, t2, "AF3 Includes_Objects.xml (blue watchlist badge without Trakt setting)")
p_lay = f"{AF3}/1080i/Includes_Layouts.xml"
if os.path.exists(p_lay):
txt = read(p_lay)
os_lay = 'condition="$PARAM[indicator] + [Skin.HasSetting(Indicator.TraktWatchlist) | Skin.HasSetting(Indicator.TraktFavourites)]"'
if os_lay in txt:
write(p_lay, txt.replace(os_lay, 'condition="$PARAM[indicator]"'), "AF3 Includes_Layouts.xml (Object_TraktOverlays always active)")
p_di = f"{AF3}/1080i/Includes_DialogInfo.xml"
if os.path.exists(p_di):
txt = read(p_di)
if 'false' in txt:
write(p_di, txt.replace('false', 'true'), "AF3 Includes_DialogInfo.xml (indicator=true)")
# 9. TMDb Helper: Read-only SQLite bridge to POV mdblcache.db
p_tmdbh_li = f"{TMDBH}/resources/tmdbhelper/lib/items/listitem.py"
if os.path.exists(p_tmdbh_li):
txt = read(p_tmdbh_li)
if "_POV_MDBL_CACHE" not in txt:
helper_block = """_POV_MDBL_CACHE = {'ts': 0, 'w_mov': set(), 'wl_mov': set(), 'wl_tv': set()}
def _apply_pov_mdbl(item):
import time, sqlite3, json
il = item.infolabels
ip = item.infoproperties
uids = item.unique_ids
params = getattr(item, 'params', {}) or {}
mt = il.get('mediatype') or params.get('tmdb_type') or ''
tid = str(uids.get('tmdb') or uids.get('tvshow.tmdb') or params.get('tmdb_id') or '')
if not tid or mt not in ('movie', 'tvshow', 'tv'):
return
now = time.time()
if now - _POV_MDBL_CACHE['ts'] > 15 or not _POV_MDBL_CACHE['w_mov']:
try:
db = '/storage/.kodi/userdata/addon_data/plugin.video.pov/mdblcache.db'
conn = sqlite3.connect(f'file:{db}?mode=ro', uri=True, timeout=2)
w_mov = {str(r[0]) for r in conn.execute("SELECT media_id FROM watched_status WHERE db_type='movie'")}
wl_mov, wl_tv = set(), set()
for (raw,) in conn.execute("SELECT data FROM mdbl_data WHERE id LIKE 'mdbl_list_contents_my_lists_%' OR id = 'mdbl_watchlist'").fetchall():
try:
parsed = json.loads(raw)
items = (parsed.get('items', []) + parsed.get('movies', []) + parsed.get('shows', [])) if isinstance(parsed, dict) else (parsed if isinstance(parsed, list) else [])
for it in items:
if not isinstance(it, dict):
continue
it_id = str(it.get('id') or it.get('tmdb_id') or '')
if not it_id:
continue
it_mt = str(it.get('mediatype') or it.get('type') or '').lower()
if it_mt in ('show', 'tv', 'tvshow'):
wl_tv.add(it_id)
elif it_mt == 'movie':
wl_mov.add(it_id)
else:
wl_mov.add(it_id)
wl_tv.add(it_id)
except Exception:
pass
conn.close()
_POV_MDBL_CACHE['w_mov'] = w_mov
_POV_MDBL_CACHE['wl_mov'] = wl_mov
_POV_MDBL_CACHE['wl_tv'] = wl_tv
_POV_MDBL_CACHE['ts'] = now
except Exception:
pass
if mt == 'movie':
if tid in _POV_MDBL_CACHE['w_mov']:
il['playcount'] = 1
il['overlay'] = 5
if tid in _POV_MDBL_CACHE['wl_mov']:
ip['watchlist_rank'] = '1'
elif mt in ('tvshow', 'tv'):
if tid in _POV_MDBL_CACHE['wl_tv']:
ip['watchlist_rank'] = '1'
"""
target = " info_tag = listitem.getVideoInfoTag()"
if target in txt:
txt = helper_block + "\n" + txt.replace(
target,
" try:\n _apply_pov_mdbl(self)\n except Exception:\n pass\n" + target,
1
)
write(p_tmdbh_li, txt, "TMDb Helper listitem.py (POV mdblcache bridge)")
with open(LOG, "a", encoding="utf-8") as f:
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"[{ts}] Changes: {', '.join(changes) if changes else 'None'}\n")