Version 4.0.0 (#182)

* Adjust refresh behavior

* Fix favorites

* Add option to mask info

* Fix keymap delete

* Fix empty show

* Version bump 3.1.14

* Reset rescan flag

* Fix subtitles encoding

* Fix path verification

* Fix update library

Plug in remove library percentage

* Fix unauthorized behavior

Reprompt user with login

* Fix series pooling

* Version bump 3.1.15

* Fix for additional users

Return all users, not just public users

* Fix http potential errors

Prevent from going further if {server} or {userid} is requested but not filled to avoid 401 errors

* Fix extra fanart

* Fix patch

make a case insensitive search

* Version bump 3.1.16

Additional logging, fix kodi source.

* Fix library tags on update

* Version bump 3.1.17

* Fix season artwork

* Fix season artwork

* Fix logging

* Fix blank files sources

* Add backup option

* Fix userdata song

* Transfer data.txt to data.json

Use default port for webserver caching

* Fix mixed content shortcut

* Fix path encoding for patch

Hopefully this works...

* Fix source nonetype error

Just incase, wrap in a try/except because it's not important.

* Base fast sync on server time

Try to fix music video refresh to prevent cursor from moving up.

* Prep subfolders for dynamic

Support homevideos for now

* Fix empty artist, missing Title

* Version bump 3.1.18a

* Version bump for objects

171076013

* Notify user of large updates

Give option to back out if the user wants to manually update the libraries

* Fix sources.xml verification

* Prevent error in monitor

Put in place try/except in case data is None

* Remember sync position for manual triggers

Allow to resume sync on restart for manual user triggers (update, repair). Automatically refresh boxsets if movie library is selected.

use waitForAbort and emby_should_stop prop to terminate threads

* Update string for sync later

* Add subfolders for dynamic movies

* Small fixes

* Version bump 3.1.19

* Fix fast sync

try/except, default back to previous behavior.

* Fix artwork

* Change settings name

To ensure it takes default value instead of previous value set in 3.0.34

* Fix transcode

flac and live tv

* Fix episodes for series pooling

* Add live tv support

* Version bump 3.1.20

* Revert "Small fixes"

This reverts commit 9ec1fa3585.

* Version bump 3.1.21

* Fix playback starting server connection instance

* Fix show update

* Fix boxsets

* Fix lastplayed

* Patch to support pre 3.6 libraries

* Fix slowness

* Plug in settings for threading

* Plug in settings for threading

* Adjust sleep behavior

* Version bump 3.1.22

* Fix server detection in monitor

* Version bump 3.1.23

* Fix potential error with checksum

* Fix missing new artists

* Fix library sync

Adjust lock, re-add screensaver deactivated during sync, prep compare sync, stop library updates from being processed before startup sync is completed

* Version bump 3.1.25

* Fix local trailers

* Adjust lock modification

* Check db version

* Prevent error from creating nodes

The addon automatically creates nodes at startup with prefilled information. Prevent errors in the event something goes wrong. It will fix itself down the line, after user has logged in.

* Version bump 3.1.26

* Revert "Version bump 3.1.26"

This reverts commit c583a69a4b.

* Fix screensaver toggle

* Fix source selection for direct stream

* Version bump 3.1.26

* Add progress for updates

* Revise progress bar

Fix typos and subsetting

* content notification

* Remove content with update library

Now remove irrelevant content as well

* Fix slowness

* Version bump 3.1.27

* Stop trying to get items if server offline

* Fix content type for dynamic music

* Fix resume sync

Now save progress, unless exited due to path validation

* Fix artwork for shortcuts on profile switch

* Add force transcode settings

* Fix audiobooks back to video type

Add shortcuts. Audiobook can't be music type otherwise it break resume behavior and it won't play the right item. Has to be video type.

* Update general info

To finish, download and installation

* Update README.md

* Move welcome message to service

* Prevent patch loop

Try once, then let it go, to avoid locking user in a restart loop

* Review library threads

* Prep for audiobook transcode

Still need to implement universal for audio transcode

* Version bump 3.1.28

* Fix emby database locked

* Fix regression to welcome message

* Version bump 3.1.29

* Adjust playback

Allow direct play for http streams

* Ensure all threads are terminated correctly

* Fix empty results due to error 500

* Fix boxset refresh

* Fix resume sync behavior

Allow to complete the startup sync in the event user backs out of resume sync

* Version bump 3.1.30

* Update patch

Move patch from cache to addon_data. No longer need to restart Kodi to apply the first patch.

* Fix inital sync leading to fast sync

* Fix user settings

Due to api change in 3.6.0.55

* krypton update

* Adjust for resume settings

With .55 the resume setting is set per library. Instead query server to see if the item is played to offer delete

* Restart service upon check for updates

To reload the new objects module.

* Fix update library

Only do the compare when user selects update library, also add a restart service option in the add-on settings > advanced

* Version bump 3.1.31

* Update dependencies

* Update FR translation

* Update DE translation

* Add translation

* Support up next

* Small service adjustment

* Krypton update to support upnext

* Add a verification onwake

Somehow, Kodi can trigger OnWake without first trigger OnSleep.

* Fix loading if special char in path

* Add logging and small fixes

Prepare userdata by date modified

* Version bump 3.1.32

* Change default behavior of startup dialog

In case it is forced closed by Kodi, allow the sync to proceed

* Ensure deliveryurl is an actual url

* Update README.md

* Fix nextup

* Fix dynamic widgets

* Detect coreelect, etc

* Fix progress report

Silent RefreshProgress in websocket

* Follow emby settings for subtitles

* Version bump 3.1.33

* Add Italian translation

* Fix playback for server 3.6.0.61

* Version bump 3.1.34a

* Add silent catch for errors

* Adjust playback progress monitor

Only track progress report if the item is an emby item

* Fix subtitles not following server settings

* Add remove libraries, fix mixed libraries

* Fix live tv

For now, use transcode since direct play returns a 127.0.0.1 unusable address as the path.

* Allow live tv to direct stream

* Fix LiveTV

* Add setting to sync during playback

* Fix updates

* Fix encoding error

* Add optional rotten tomatoes option

* Version bump 3.1.35

* Fix emby connect auth string

Was preventing proper device detection when using emby connect, play to, etc.

* Add setup RT

* Fix audio/sub change

Only for addon playback

* Add developer mode

* Update patch

Check for updates + dev = forced grab from github

* Fix RT string

* Fix patch

Allow dev mode to redownload zip

* Fix patch

ugh sleep!!

* Verify patch connection

* Version bump 3.1.36

* Fix libraries being wiped

Catch errors to prevent false positive

* Add dateutil library

* Prep convert to local time

* Fix string

* Prep for multi db version support

* Fix service restart

* Add shortcut restart addon

Add notification

* Add database discovery

* Ensure previous playback terminated

* Update translation

New: Polish, Dutch Updated: German, French, Italian

* Version bump 3.1.37

* Quick fix for new library dateutil

* Catch error for dateutil

In the event the server has some weird date that can't be converted

* Version bump 3.1.38

* Fix dateutil import

* Fix db discovery

Ignore emby.db

* Version bump 3.1.39

* Add a delay if setup not completed

Avoid crash from everything loading at once.

* Fix database discovery

Add table verification + date modified verification

* Container optional playutils

* Version bump 3.1.40

* Adjust database discovery

Compare loaded vs discovered to avoid loading old databases by accident.

* Version bump 3.1.41

* Fix discovery toggle

* Version bump 3.1.42

* Add webservice for playback prep

* Fix service restart

* Version bump 3.1.43

* Update default sync indicator

Based on overall feedback

* Fix check update

* Fix if server is selected but unavailable

* Support songs without albums

* Fix encode and params

* Increase retry timeout

* Fix update generating duplicates

* Add manage libraries

Too many entries

* Fix database discovery

* Fixed transcode via context menu

* Fix context transcode

* Quiet webservice

* Update Krypton objects

* Fix database discovery prompt

* fixed video listitem issues for krypton

* load all item details for playlists

* Fix playlist

* Version bump 3.1.44

* Fix force hi10p transcoding behavior

Fixes the "Force Hi10p transcoding" option to only apply to h264 video codecs

* Clear playlist on player.onstop

* Don't clear playlist if busy spinner is active

* Fix case sensitive issue at calling the log function

* fix db stuff (#164)

* Reload objects upon initial setup

* Fix database discovery

ignore db-journal

* Update translation

German, Italian

* Use LastConnectionMode for server test

* Fix compare sync

* Version bump 3.1.45

* Ensure widgets get updated

Container.Refresh alone doesn't seem to work

* Update database discovery

* Re-add texture to database discovery

* Add option to enable/disable service

* Remove unused strings

* Fix object reload upon restart service

* Update Krypton objects

* Update translation

Dutch, Polish

* Version bump 3.1.46

* Adjust client api

* Adjust subtitles behavior

* Fix string typo

* Only run one full sync instance

Prevent user from launching multiple syncs and freezing the add-on.

* added "playlists" to wnodes

* Disable Audiobooks

Server doesn't have a set structure yet. This feature is broken atm.

* Version bump 4.0.0

* License GPL v3

* Update readme
This commit is contained in:
angelblue05 2019-01-24 07:04:48 -06:00 committed by GitHub
parent b8613e1e66
commit bab67ddf9b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
349 changed files with 67373 additions and 21636 deletions

View file

@ -0,0 +1,26 @@
from translate import _
from exceptions import LibraryException
from utils import addon_id
from utils import window
from utils import settings
from utils import kodi_version
from utils import dialog
from utils import find
from utils import event
from utils import validate
from utils import values
from utils import JSONRPC
from utils import indent
from utils import write_xml
from utils import compare_version
from utils import unzip
from utils import create_id
from utils import convert_to_local as Local
from wrapper import progress
from wrapper import catch
from wrapper import silent_catch
from wrapper import stop
from wrapper import emby_item
from wrapper import library_check

334
resources/lib/helper/api.py Normal file
View file

@ -0,0 +1,334 @@
# -*- coding: utf-8 -*-
##################################################################################################
import json
import datetime
import logging
from . import settings
##################################################################################################
LOG = logging.getLogger("EMBY."+__name__)
##################################################################################################
class API(object):
def __init__(self, item, server=None):
''' Get item information in special cases.
server is the server address, provide if your functions requires it.
'''
self.item = item
self.server = server
def get_playcount(self, played, playcount):
''' Convert Emby played/playcount into
the Kodi equivalent. The playcount is tied to the watch status.
'''
return (playcount or 1) if played else None
def get_naming(self):
if self.item['Type'] == 'Episode':
if 'SeriesName' in self.item:
return "%s: %s" % (self.item['SeriesName'], self.item['Name'])
elif self.item['Type'] == 'MusicAlbum':
if 'AlbumArtist' in self.item:
return "%s: %s" % (self.item['AlbumArtist'], self.item['Name'])
elif self.item['Type'] == 'Audio':
if self.item.get('Artists'):
return "%s: %s" % (self.item['Artists'][0], self.item['Name'])
return self.item['Name']
def get_actors(self):
cast = []
if 'People' in self.item:
self.get_people_artwork(self.item['People'])
for person in self.item['People']:
if person['Type'] == "Actor":
cast.append({
'name': person['Name'],
'role': person.get('Role', "Unknown"),
'order': len(cast) + 1,
'thumbnail': person['imageurl']
})
return cast
def media_streams(self, video, audio, subtitles):
return {
'video': video or [],
'audio': audio or [],
'subtitle': subtitles or []
}
def video_streams(self, tracks, container=None):
if container:
container = container.split(',')[0]
for track in tracks:
track.update({
'codec': track.get('Codec', "").lower(),
'profile': track.get('Profile', "").lower(),
'height': track.get('Height'),
'width': track.get('Width'),
'3d': self.item.get('Video3DFormat'),
'aspect': 1.85
})
if "msmpeg4" in track['codec']:
track['codec'] = "divx"
elif "mpeg4" in track['codec']:
if "simple profile" in track['profile'] or not track['profile']:
track['codec'] = "xvid"
elif "h264" in track['codec']:
if container in ('mp4', 'mov', 'm4v'):
track['codec'] = "avc1"
try:
width, height = self.item.get('AspectRatio', track.get('AspectRatio', "0")).split(':')
track['aspect'] = round(float(width) / float(height), 6)
except (ValueError, ZeroDivisionError):
if track['width'] and track['height']:
track['aspect'] = round(float(track['width'] / track['height']), 6)
track['duration'] = self.get_runtime()
return tracks
def audio_streams(self, tracks):
for track in tracks:
track.update({
'codec': track.get('Codec', "").lower(),
'profile': track.get('Profile', "").lower(),
'channels': track.get('Channels'),
'language': track.get('Language')
})
if "dts-hd ma" in track['profile']:
track['codec'] = "dtshd_ma"
elif "dts-hd hra" in track['profile']:
track['codec'] = "dtshd_hra"
return tracks
def get_runtime(self):
try:
runtime = self.item['RunTimeTicks'] / 10000000.0
except KeyError:
runtime = self.item.get('CumulativeRunTimeTicks', 0) / 10000000.0
return runtime
@classmethod
def adjust_resume(cls, resume_seconds):
resume = 0
if resume_seconds:
resume = round(float(resume_seconds), 6)
jumpback = int(settings('resumeJumpBack'))
if resume > jumpback:
# To avoid negative bookmark
resume = resume - jumpback
return resume
def validate_studio(self, studio_name):
# Convert studio for Kodi to properly detect them
studios = {
'abc (us)': "ABC",
'fox (us)': "FOX",
'mtv (us)': "MTV",
'showcase (ca)': "Showcase",
'wgn america': "WGN",
'bravo (us)': "Bravo",
'tnt (us)': "TNT",
'comedy central': "Comedy Central (US)"
}
return studios.get(studio_name.lower(), studio_name)
def get_overview(self, overview=None):
overview = overview or self.item.get('Overview')
if not overview:
return
overview = overview.replace("\"", "\'")
overview = overview.replace("\n", "[CR]")
overview = overview.replace("\r", " ")
overview = overview.replace("<br>", "[CR]")
return overview
def get_mpaa(self, rating=None):
mpaa = rating or self.item.get('OfficialRating', "")
if mpaa in ("NR", "UR"):
# Kodi seems to not like NR, but will accept Not Rated
mpaa = "Not Rated"
if "FSK-" in mpaa:
mpaa = mpaa.replace("-", " ")
return mpaa
def get_file_path(self, path=None):
if path is None:
path = self.item.get('Path')
if not path:
return ""
if path.startswith('\\\\'):
path = path.replace('\\\\', "smb://", 1).replace('\\\\', "\\").replace('\\', "/")
if 'Container' in self.item:
if self.item['Container'] == 'dvd':
path = "%s/VIDEO_TS/VIDEO_TS.IFO" % path
elif self.item['Container'] == 'bluray':
path = "%s/BDMV/index.bdmv" % path
path = path.replace('\\\\', "\\")
if '\\' in path:
path = path.replace('/', "\\")
if '://' in path:
protocol = path.split('://')[0]
path = path.replace(protocol, protocol.lower())
return path
def get_user_artwork(self, user_id):
''' Get emby user profile picture.
'''
return "%s/emby/Users/%s/Images/Primary?Format=original" % (self.server, user_id)
def get_people_artwork(self, people):
''' Get people (actor, director, etc) artwork.
'''
for person in people:
if 'PrimaryImageTag' in person:
query = "&MaxWidth=400&MaxHeight=400&Index=0"
person['imageurl'] = self.get_artwork(person['Id'], "Primary", person['PrimaryImageTag'], query)
else:
person['imageurl'] = None
return people
def get_all_artwork(self, obj, parent_info=False):
''' Get all artwork possible. If parent_info is True,
it will fill missing artwork with parent artwork.
obj is from objects.Objects().map(item, 'Artwork')
'''
query = ""
all_artwork = {
'Primary': "",
'BoxRear': "",
'Art': "",
'Banner': "",
'Logo': "",
'Thumb': "",
'Disc': "",
'Backdrop': []
}
if settings('compressArt.bool'):
query = "&Quality=90"
if not settings('enableCoverArt.bool'):
query += "&EnableImageEnhancers=false"
all_artwork['Backdrop'] = self.get_backdrops(obj['Id'], obj['BackdropTags'] or [], query)
for artwork in (obj['Tags'] or []):
all_artwork[artwork] = self.get_artwork(obj['Id'], artwork, obj['Tags'][artwork], query)
if parent_info:
if not all_artwork['Backdrop'] and obj['ParentBackdropId']:
all_artwork['Backdrop'] = self.get_backdrops(obj['ParentBackdropId'], obj['ParentBackdropTags'], query)
for art in ('Logo', 'Art', 'Thumb'):
if not all_artwork[art] and obj['Parent%sId' % art]:
all_artwork[art] = self.get_artwork(obj['Parent%sId' % art], art, obj['Parent%sTag' % art], query)
if obj.get('SeriesTag'):
all_artwork['Series.Primary'] = self.get_artwork(obj['SeriesId'], "Primary", obj['SeriesTag'], query)
if not all_artwork['Primary']:
all_artwork['Primary'] = all_artwork['Series.Primary']
elif not all_artwork['Primary'] and obj.get('AlbumId'):
all_artwork['Primary'] = self.get_artwork(obj['AlbumId'], "Primary", obj['AlbumTag'], query)
return all_artwork
def get_backdrops(self, item_id, tags, query=None):
''' Get backdrops based of "BackdropImageTags" in the emby object.
'''
backdrops = []
if item_id is None:
return backdrops
for index, tag in enumerate(tags):
artwork = "%s/emby/Items/%s/Images/Backdrop/%s?Format=original&Tag=%s%s" % (self.server, item_id, index, tag, (query or ""))
backdrops.append(artwork)
return backdrops
def get_artwork(self, item_id, image, tag=None, query=None):
''' Get any type of artwork: Primary, Art, Banner, Logo, Thumb, Disc
'''
if item_id is None:
return ""
url = "%s/emby/Items/%s/Images/%s/0?Format=original" % (self.server, item_id, image)
if tag is not None:
url += "&Tag=%s" % tag
if query is not None:
url += query or ""
return url

View file

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
#################################################################################################
class LibraryException(Exception):
# Emby library sync exception
def __init__(self, status):
self.status = status

View file

@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
##################################################################################################
import logging
import xbmc
import database
from . import window, settings
##################################################################################################
def config():
logger = logging.getLogger('EMBY')
logger.addHandler(LogHandler())
logger.setLevel(logging.DEBUG)
def reset():
for handler in logging.getLogger('EMBY').handlers:
logging.getLogger('EMBY').removeHandler(handler)
class LogHandler(logging.StreamHandler):
def __init__(self):
logging.StreamHandler.__init__(self)
self.setFormatter(MyFormatter())
self.sensitive = {'Token': [], 'Server': []}
for server in database.get_credentials()['Servers']:
if server.get('AccessToken'):
self.sensitive['Token'].append(server['AccessToken'])
if server.get('LocalAddress'):
self.sensitive['Server'].append(server['LocalAddress'].split('://')[1])
if server.get('RemoteAddress'):
self.sensitive['Server'].append(server['RemoteAddress'].split('://')[1])
if server.get('ManualAddress'):
self.sensitive['Server'].append(server['ManualAddress'].split('://')[1])
self.mask_info = settings('maskInfo.bool')
def emit(self, record):
if self._get_log_level(record.levelno):
string = self.format(record)
if self.mask_info:
for server in self.sensitive['Server']:
string = string.replace(server.encode('utf-8') or "{server}", "{emby-server}")
for token in self.sensitive['Token']:
string = string.replace(token.encode('utf-8') or "{token}", "{emby-token}")
try:
xbmc.log(string, level=xbmc.LOGNOTICE)
except UnicodeEncodeError:
xbmc.log(string.encode('utf-8'), level=xbmc.LOGNOTICE)
@classmethod
def _get_log_level(cls, level):
levels = {
logging.ERROR: 0,
logging.WARNING: 0,
logging.INFO: 1,
logging.DEBUG: 2
}
try:
log_level = int(window('emby_logLevel'))
except ValueError:
log_level = 0
return log_level >= levels[level]
class MyFormatter(logging.Formatter):
def __init__(self, fmt="%(name)s -> %(message)s"):
logging.Formatter.__init__(self, fmt)
def format(self, record):
# Save the original format configured by the user
# when the logger formatter was instantiated
format_orig = self._fmt
# Replace the original format with one customized by logging level
if record.levelno in (logging.DEBUG, logging.ERROR):
self._fmt = '%(name)s -> %(levelname)s:: %(message)s'
# Call the original formatter class to do the grunt work
result = logging.Formatter.format(self, record)
# Restore the original format configured by the user
self._fmt = format_orig
return result

View file

@ -0,0 +1,634 @@
# -*- coding: utf-8 -*-
#################################################################################################
import json
import logging
import os
from uuid import uuid4
import xbmc
import xbmcvfs
import api
import database
import client
import collections
from . import _, settings, window, dialog
from libraries import requests
from downloader import TheVoid
from emby import Emby
#################################################################################################
LOG = logging.getLogger("EMBY."+__name__)
#################################################################################################
def set_properties(item, method, server_id=None):
''' Set all properties for playback detection.
'''
info = item.get('PlaybackInfo') or {}
current = window('emby_play.json') or []
current.append({
'Type': item['Type'],
'Id': item['Id'],
'Path': info['Path'],
'PlayMethod': method,
'PlayOption': 'Addon' if info.get('PlaySessionId') else 'Native',
'MediaSourceId': info.get('MediaSourceId', item['Id']),
'Runtime': item.get('RunTimeTicks'),
'PlaySessionId': info.get('PlaySessionId', str(uuid4()).replace("-", "")),
'ServerId': server_id,
'DeviceId': client.get_device_id(),
'SubsMapping': info.get('Subtitles'),
'AudioStreamIndex': info.get('AudioStreamIndex'),
'SubtitleStreamIndex': info.get('SubtitleStreamIndex'),
'CurrentPosition': info.get('CurrentPosition'),
'CurrentEpisode': info.get('CurrentEpisode')
})
window('emby_play.json', current)
class PlayUtils(object):
def __init__(self, item, force_transcode=False, server_id=None, server=None, token=None):
''' Item will be updated with the property PlaybackInfo, which
holds all the playback information.
'''
self.item = item
self.item['PlaybackInfo'] = {}
self.info = {
'ServerId': server_id,
'ServerAddress': server,
'ForceTranscode': force_transcode,
'Token': token or TheVoid('GetToken', {'ServerId': server_id}).get()
}
def get_sources(self, source_id=None):
''' Return sources based on the optional source_id or the device profile.
'''
params = {
'ServerId': self.info['ServerId'],
'Id': self.item['Id'],
'Profile': self.get_device_profile()
}
info = TheVoid('GetPlaybackInfo', params).get()
LOG.info(info)
self.info['PlaySessionId'] = info['PlaySessionId']
sources = []
if not info.get('MediaSources'):
LOG.info("No MediaSources found.")
elif source_id:
for source in info:
if source['Id'] == source_id:
sources.append(source)
break
elif not self.is_selection(info) or len(info['MediaSources']) == 1:
LOG.info("Skip source selection.")
sources.append(info['MediaSources'][0])
else:
sources.extend([x for x in info['MediaSources']])
return sources
def select_source(self, sources, audio=None, subtitle=None):
if len(sources) > 1:
selection = []
for source in sources:
selection.append(source.get('Name', "na"))
resp = dialog("select", _(33130), selection)
if resp > -1:
source = sources[resp]
else:
LOG.info("No media source selected.")
return False
else:
source = sources[0]
self.get(source, audio, subtitle)
return source
def is_selection(self, sources):
''' Do not allow source selection for.
'''
if self.item['MediaType'] != 'Video':
LOG.debug("MediaType is not a video.")
return False
elif self.item['Type'] == 'TvChannel':
LOG.debug("TvChannel detected.")
return False
elif len(sources) == 1 and sources[0]['Type'] == 'Placeholder':
LOG.debug("Placeholder detected.")
return False
elif 'SourceType' in self.item and self.item['SourceType'] != 'Library':
LOG.debug("SourceType not from library.")
return False
return True
def is_file_exists(self, source):
path = self.direct_play(source)
if xbmcvfs.exists(self.info['Path']):
LOG.info("Path exists.")
return True
LOG.info("Failed to find file.")
return False
def is_strm(self, source):
if source.get('Container') == 'strm' or self.item['Path'].endswith('.strm'):
LOG.info("strm detected")
return True
return False
def get(self, source, audio=None, subtitle=None):
''' The server returns sources based on the MaxStreamingBitrate value and other filters.
prop: embyfilename for ?? I thought it was to pass the real path to subtitle add-ons but it's not working?
'''
self.info['MediaSourceId'] = source['Id']
if source.get('RequiresClosing'):
''' Server returning live tv stream for direct play is hardcoded with 127.0.0.1.
'''
self.info['LiveStreamId'] = source['LiveStreamId']
source['SupportsDirectPlay'] = False
source['Protocol'] = "LiveTV"
if self.info['ForceTranscode']:
source['SupportsDirectPlay'] = False
source['SupportsDirectStream'] = False
if source.get('Protocol') == 'Http' or source['SupportsDirectPlay'] and (self.is_strm(source) or not settings('playFromStream.bool') and self.is_file_exists(source)):
LOG.info("--[ direct play ]")
self.direct_play(source)
elif source['SupportsDirectStream']:
LOG.info("--[ direct stream ]")
self.direct_url(source)
else:
LOG.info("--[ transcode ]")
self.transcode(source, audio, subtitle)
self.info['AudioStreamIndex'] = self.info.get('AudioStreamIndex') or source.get('DefaultAudioStreamIndex')
self.info['SubtitleStreamIndex'] = self.info.get('SubtitleStreamIndex') or source.get('DefaultSubtitleStreamIndex')
self.item['PlaybackInfo'].update(self.info)
API = api.API(self.item, self.info['ServerAddress'])
window('embyfilename', value=API.get_file_path(source.get('Path')).encode('utf-8'))
def live_stream(self, source):
''' Get live stream media info.
'''
params = {
'ServerId': self.info['ServerId'],
'Id': self.item['Id'],
'Profile': self.get_device_profile(),
'PlaySessionId': self.info['PlaySessionId'],
'Token': source['OpenToken']
}
info = TheVoid('GetLiveStream', params).get()
LOG.info(info)
if info['MediaSource'].get('RequiresClosing'):
self.info['LiveStreamId'] = source['LiveStreamId']
return info['MediaSource']
def transcode(self, source, audio=None, subtitle=None):
if not 'TranscodingUrl' in source:
raise Exception("use get_sources to get transcoding url")
self.info['Method'] = "Transcode"
if self.item['MediaType'] == 'Video':
base, params = source['TranscodingUrl'].split('?')
if settings('skipDialogTranscode') != "3" and source.get('MediaStreams'):
url_parsed = params.split('&')
for i in url_parsed:
if 'AudioStreamIndex' in i or 'AudioBitrate' in i or 'SubtitleStreamIndex' in i: # handle manually
url_parsed.remove(i)
params = "%s%s" % ('&'.join(url_parsed), self.get_audio_subs(source, audio, subtitle))
video_type = 'live' if source['Protocol'] == 'LiveTV' else 'master'
base = base.replace('stream' if 'stream' in base else 'master', video_type, 1)
self.info['Path'] = "%s/emby%s?%s" % (self.info['ServerAddress'], base, params)
self.info['Path'] += "&maxWidth=%s&maxHeight=%s" % (self.get_resolution())
else:
self.info['Path'] = "%s/emby%s" % (self.info['ServerAddress'], source['TranscodingUrl'])
return self.info['Path']
def direct_play(self, source):
API = api.API(self.item, self.info['ServerAddress'])
self.info['Method'] = "DirectPlay"
self.info['Path'] = API.get_file_path(source.get('Path'))
return self.info['Path']
def direct_url(self, source):
self.info['Method'] = "DirectStream"
if self.item['Type'] == "Audio":
self.info['Path'] = ("%s/emby/Audio/%s/stream.%s?static=true&api_key=%s" %
(self.info['ServerAddress'], self.item['Id'],
source.get('Container', "mp4").split(',')[0],
self.info['Token']))
else:
self.info['Path'] = ("%s/emby/Videos/%s/stream?static=true&MediaSourceId=%s&api_key=%s" %
(self.info['ServerAddress'], self.item['Id'], source['Id'], self.info['Token']))
return self.info['Path']
def get_bitrate(self):
''' Get the video quality based on add-on settings.
Max bit rate supported by server: 2147483 (max signed 32bit integer)
'''
bitrate = [664, 996, 1320, 2000, 3200,
4700, 6200, 7700, 9200, 10700,
12200, 13700, 15200, 16700, 18200,
20000, 25000, 30000, 35000, 40000,
100000, 1000000, 2147483]
return bitrate[int(settings('videoBitrate') or 22)]
def get_resolution(self):
return int(xbmc.getInfoLabel('System.ScreenWidth')), int(xbmc.getInfoLabel('System.ScreenHeight'))
def get_device_profile(self):
''' Get device profile based on the add-on settings.
'''
profile = {
"Name": "Kodi",
"MaxStreamingBitrate": self.get_bitrate() * 1000,
"MusicStreamingTranscodingBitrate": 1280000,
"TimelineOffsetSeconds": 5,
"TranscodingProfiles": [
{
"Type": "Audio"
},
{
"Container": "m3u8",
"Type": "Video",
"AudioCodec": "aac,mp3,ac3,opus,flac,vorbis",
"VideoCodec": "h264,mpeg4,mpeg2video",
"MaxAudioChannels": "6"
},
{
"Container": "jpeg",
"Type": "Photo"
}
],
"DirectPlayProfiles": [
{
"Type": "Video"
},
{
"Type": "Audio"
},
{
"Type": "Photo"
}
],
"ResponseProfiles": [],
"ContainerProfiles": [],
"CodecProfiles": [],
"SubtitleProfiles": [
{
"Format": "srt",
"Method": "External"
},
{
"Format": "srt",
"Method": "Embed"
},
{
"Format": "ass",
"Method": "External"
},
{
"Format": "ass",
"Method": "Embed"
},
{
"Format": "sub",
"Method": "Embed"
},
{
"Format": "sub",
"Method": "External"
},
{
"Format": "ssa",
"Method": "Embed"
},
{
"Format": "ssa",
"Method": "External"
},
{
"Format": "smi",
"Method": "Embed"
},
{
"Format": "smi",
"Method": "External"
},
{
"Format": "pgssub",
"Method": "Embed"
},
{
"Format": "pgssub",
"Method": "External"
},
{
"Format": "dvdsub",
"Method": "Embed"
},
{
"Format": "dvdsub",
"Method": "External"
},
{
"Format": "pgs",
"Method": "Embed"
},
{
"Format": "pgs",
"Method": "External"
}
]
}
if settings('transcode_h265.bool'):
profile['DirectPlayProfiles'][0]['VideoCodec'] = "h264,mpeg4,mpeg2video"
else:
profile['TranscodingProfiles'].insert(0, {
"Container": "m3u8",
"Type": "Video",
"AudioCodec": "aac,mp3,ac3,opus,flac,vorbis",
"VideoCodec": "h264,h265,hevc,mpeg4,mpeg2video",
"MaxAudioChannels": "6"
})
if settings('transcodeHi10P.bool'):
profile['CodecProfiles'].append(
{
'Type': 'Video',
'codec': 'h264',
'Conditions': [
{
'Condition': "LessThanEqual",
'Property': "VideoBitDepth",
'Value': "8"
}
]
}
)
if self.info['ForceTranscode']:
profile['DirectPlayProfiles'] = []
if self.item['Type'] == 'TvChannel':
profile['TranscodingProfiles'].insert(0, {
"Container": "ts",
"Type": "Video",
"AudioCodec": "mp3,aac",
"VideoCodec": "h264",
"Context": "Streaming",
"Protocol": "hls",
"MaxAudioChannels": "2",
"MinSegments": "1",
"BreakOnNonKeyFrames": True
})
return profile
def set_external_subs(self, source, listitem):
''' Try to download external subs locally so we can label them.
Since Emby returns all possible tracks together, sort them.
IsTextSubtitleStream if true, is available to download from server.
'''
if not settings('enableExternalSubs.bool') or not source['MediaStreams']:
return
subs = []
mapping = {}
kodi = 0
for stream in source['MediaStreams']:
if stream['Type'] == 'Subtitle' and stream['IsExternal']:
index = stream['Index']
if 'DeliveryUrl' in stream and stream['DeliveryUrl'].lower().startswith('/videos'):
url = "%s/emby%s" % (self.info['ServerAddress'], stream['DeliveryUrl'])
else:
url = self.get_subtitles(source, stream, index)
if url is None:
continue
LOG.info("[ subtitles/%s ] %s", index, url)
if 'Language' in stream:
filename = "Stream.%s.%s" % (stream['Language'].encode('utf-8'), stream['Codec'].encode('utf-8'))
try:
subs.append(self.download_external_subs(url, filename))
except Exception as error:
LOG.error(error)
subs.append(url)
else:
subs.append(url)
mapping[kodi] = index
kodi += 1
listitem.setSubtitles(subs)
self.item['PlaybackInfo']['Subtitles'] = mapping
@classmethod
def download_external_subs(cls, src, filename):
''' Download external subtitles to temp folder
to be able to have proper names to streams.
'''
temp = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/temp/").decode('utf-8')
if not xbmcvfs.exists(temp):
xbmcvfs.mkdir(temp)
path = os.path.join(temp, filename)
try:
response = requests.get(src, stream=True, verify=False)
response.raise_for_status()
except Exception as e:
raise
else:
response.encoding = 'utf-8'
with open(path, 'wb') as f:
f.write(response.content)
del response
return path
def get_audio_subs(self, source, audio=None, subtitle=None):
''' For transcoding only
Present the list of audio/subs to select from, before playback starts.
Since Emby returns all possible tracks together, sort them.
IsTextSubtitleStream if true, is available to download from server.
'''
prefs = ""
audio_streams = collections.OrderedDict()
subs_streams = collections.OrderedDict()
streams = source['MediaStreams']
for stream in streams:
index = stream['Index']
stream_type = stream['Type']
if stream_type == 'Audio':
codec = stream['Codec']
channel = stream.get('ChannelLayout', "")
if 'Language' in stream:
track = "%s - %s - %s %s" % (index, stream['Language'], codec, channel)
else:
track = "%s - %s %s" % (index, codec, channel)
audio_streams[track] = index
elif stream_type == 'Subtitle':
if 'Language' in stream:
track = "%s - %s" % (index, stream['Language'])
else:
track = "%s - %s" % (index, stream['Codec'])
if stream['IsDefault']:
track = "%s - Default" % track
if stream['IsForced']:
track = "%s - Forced" % track
subs_streams[track] = index
skip_dialog = int(settings('skipDialogTranscode') or 0)
audio_selected = None
if audio:
audio_selected = audio
elif skip_dialog in (0, 1):
if len(audio_streams) > 1:
selection = list(audio_streams.keys())
resp = dialog("select", _(33013), selection)
audio_selected = audio_streams[selection[resp]] if resp else source['DefaultAudioStreamIndex']
else: # Only one choice
audio_selected = audio_streams[next(iter(audio_streams))]
else:
audio_selected = source['DefaultAudioStreamIndex']
self.info['AudioStreamIndex'] = audio_selected
prefs += "&AudioStreamIndex=%s" % audio_selected
prefs += "&AudioBitrate=384000" if streams[audio_selected].get('Channels', 0) > 2 else "&AudioBitrate=192000"
if subtitle:
index = subtitle
server_settings = TheVoid('GetTranscodeOptions', {'ServerId': self.info['ServerId']}).get()
stream = streams[index]
if server_settings['EnableSubtitleExtraction'] and stream['SupportsExternalStream']:
self.info['SubtitleUrl'] = self.get_subtitles(source, stream, index)
else:
prefs += "&SubtitleStreamIndex=%s" % index
self.info['SubtitleStreamIndex'] = index
elif skip_dialog in (0, 2) and len(subs_streams):
selection = list(['No subtitles']) + list(subs_streams.keys())
resp = dialog("select", _(33014), selection)
if resp:
index = subs_streams[selection[resp]] if resp > -1 else source.get('DefaultSubtitleStreamIndex')
if index is not None:
server_settings = TheVoid('GetTranscodeOptions', {'ServerId': self.info['ServerId']}).get()
stream = streams[index]
if server_settings['EnableSubtitleExtraction'] and stream['SupportsExternalStream']:
self.info['SubtitleUrl'] = self.get_subtitles(source, stream, index)
else:
prefs += "&SubtitleStreamIndex=%s" % index
self.info['SubtitleStreamIndex'] = index
return prefs
def get_subtitles(self, source, stream, index):
if stream['IsTextSubtitleStream'] and 'DeliveryUrl' in stream and stream['DeliveryUrl'].lower().startswith('/videos'):
url = "%s/emby%s" % (self.info['ServerAddress'], stream['DeliveryUrl'])
else:
url = ("%s/emby/Videos/%s/%s/Subtitles/%s/Stream.%s?api_key=%s" %
(self.info['ServerAddress'], self.item['Id'], source['Id'], index, stream['Codec'], self.info['Token']))
return url

View file

@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
##################################################################################################
import json
import logging
import os
import xbmc
import xbmcaddon
##################################################################################################
LOG = logging.getLogger('EMBY.'+__name__)
##################################################################################################
def _(string):
''' Get add-on string. Returns in unicode.
'''
if type(string) != int:
string = STRINGS[string]
result = xbmcaddon.Addon('plugin.video.emby').getLocalizedString(string)
if not result:
result = xbmc.getLocalizedString(string)
return result
STRINGS = {
'addon_name': 29999,
'playback_mode': 30511,
'empty_user': 30613,
'empty_user_pass': 30608,
'empty_server': 30617,
'network_credentials': 30517,
'invalid_auth': 33009,
'addon_mode': 33036,
'native_mode': 33037,
'cancel': 30606,
'username': 30024,
'password': 30602,
'gathering': 33021,
'boxsets': 30185,
'movies': 30302,
'tvshows': 30305,
'fav_movies': 30180,
'fav_tvshows': 30181,
'fav_episodes': 30182
}

View file

@ -0,0 +1,463 @@
# -*- coding: utf-8 -*-
#################################################################################################
import binascii
import json
import logging
import os
import re
import unicodedata
import urllib
from uuid import uuid4
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
from . import _
#################################################################################################
LOG = logging.getLogger("EMBY."+__name__)
#################################################################################################
def addon_id():
return "plugin.video.emby"
def kodi_version():
return xbmc.getInfoLabel('System.BuildVersion')[:2]
def window(key, value=None, clear=False, window_id=10000):
''' Get or set window properties.
'''
window = xbmcgui.Window(window_id)
if clear:
LOG.debug("--[ window clear: %s ]", key)
window.clearProperty(key.replace('.json', "").replace('.bool', ""))
elif value is not None:
if key.endswith('.json'):
key = key.replace('.json', "")
value = json.dumps(value)
elif key.endswith('.bool'):
key = key.replace('.bool', "")
value = "true" if value else "false"
window.setProperty(key.replace('.json', "").replace('.bool', ""), value)
else:
result = window.getProperty(key.replace('.json', "").replace('.bool', ""))
if result:
if key.endswith('.json'):
result = json.loads(result)
elif key.endswith('.bool'):
result = result in ("true", "1")
return result
def settings(setting, value=None):
''' Get or add add-on settings.
getSetting returns unicode object.
'''
addon = xbmcaddon.Addon(addon_id())
if value is not None:
if setting.endswith('.bool'):
setting = setting.replace('.bool', "")
value = "true" if value else "false"
addon.setSetting(setting, value)
else:
result = addon.getSetting(setting.replace('.bool', ""))
if result and setting.endswith('.bool'):
result = result in ("true", "1")
return result
def create_id():
return uuid4()
def compare_version(a, b):
''' -1 a is smaller
1 a is larger
0 equal
'''
a = a.split('.')
b = b.split('.')
for i in range(0, max(len(a), len(b)), 1):
try:
aVal = a[i]
except IndexError:
aVal = 0
try:
bVal = b[i]
except IndexError:
bVal = 0
if aVal < bVal:
return -1
if aVal > bVal:
return 1
return 0
def find(dict, item):
''' Find value in dictionary.
'''
if item in dict:
return dict[item]
for key,value in sorted(dict.iteritems(), key=lambda (k,v): (v,k)):
if re.match(key, item, re.I):
return dict[key]
def event(method, data=None, sender=None, hexlify=False):
''' Data is a dictionary.
'''
data = data or {}
sender = sender or "plugin.video.emby"
if hexlify:
data = '\\"[\\"{0}\\"]\\"'.format(binascii.hexlify(json.dumps(data)))
else:
data = '"[%s]"' % json.dumps(data).replace('"', '\\"')
xbmc.executebuiltin('NotifyAll(%s, %s, %s)' % (sender, method, data))
LOG.debug("---[ event: %s/%s ] %s", sender, method, data)
def dialog(dialog_type, *args, **kwargs):
d = xbmcgui.Dialog()
if "icon" in kwargs:
kwargs['icon'] = kwargs['icon'].replace("{emby}",
"special://home/addons/plugin.video.emby/icon.png")
if "heading" in kwargs:
kwargs['heading'] = kwargs['heading'].replace("{emby}", _('addon_name'))
types = {
'yesno': d.yesno,
'ok': d.ok,
'notification': d.notification,
'input': d.input,
'select': d.select,
'numeric': d.numeric,
'multi': d.multiselect
}
return types[dialog_type](*args, **kwargs)
def should_stop():
''' Checkpoint during the sync process.
'''
if xbmc.Monitor().waitForAbort(0.00001):
return True
if window('emby_should_stop.bool'):
LOG.info("exiiiiitttinggg")
return True
if not window('emby_online.bool'):
return True
return False
def get_screensaver():
''' Get the current screensaver value.
'''
result = JSONRPC('Settings.getSettingValue').execute({'setting': "screensaver.mode"})
try:
return result['result']['value']
except KeyError:
return ""
def set_screensaver(value):
''' Toggle the screensaver
'''
params = {
'setting': "screensaver.mode",
'value': value
}
result = JSONRPC('Settings.setSettingValue').execute(params)
LOG.info("---[ screensaver/%s ] %s", value, result)
class JSONRPC(object):
version = 1
jsonrpc = "2.0"
def __init__(self, method, **kwargs):
self.method = method
for arg in kwargs:
self.arg = arg
def _query(self):
query = {
'jsonrpc': self.jsonrpc,
'id': self.version,
'method': self.method,
}
if self.params is not None:
query['params'] = self.params
return json.dumps(query)
def execute(self, params=None):
self.params = params
return json.loads(xbmc.executeJSONRPC(self._query()))
def validate(path):
''' Verify if path is accessible.
'''
if window('emby_pathverified.bool'):
return True
path = path if os.path.supports_unicode_filenames else path.encode('utf-8')
if not xbmcvfs.exists(path):
LOG.info("Could not find %s", path)
if dialog("yesno", heading="{emby}", line1="%s %s. %s" % (_(33047), path, _(33048))):
return False
window('emby_pathverified.bool', True)
return True
def values(item, keys):
''' Grab the values in the item for a list of keys {key},{key1}....
If the key has no brackets, the key will be passed as is.
'''
return (item[key.replace('{', "").replace('}', "")] if type(key) == str and key.startswith('{') else key for key in keys)
def indent(elem, level=0):
''' Prettify xml docs.
'''
try:
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
except Exception:
return
def write_xml(content, file):
with open(file, 'w') as infile:
content = content.replace("'", '"')
content = content.replace('?>', ' standalone="yes" ?>', 1)
infile.write(content)
def delete_folder(path=None):
''' Delete objects from kodi cache
'''
LOG.debug("--[ delete folder ]")
delete_path = path is not None
path = path or xbmc.translatePath('special://temp/emby').decode('utf-8')
dirs, files = xbmcvfs.listdir(path)
delete_recursive(path, dirs)
for file in files:
xbmcvfs.delete(os.path.join(path, file.decode('utf-8')))
if delete_path:
xbmcvfs.delete(path)
LOG.info("DELETE %s", path)
def delete_recursive(path, dirs):
''' Delete files and dirs recursively.
'''
for directory in dirs:
dirs2, files = xbmcvfs.listdir(os.path.join(path, directory.decode('utf-8')))
for file in files:
xbmcvfs.delete(os.path.join(path, directory.decode('utf-8'), file.decode('utf-8')))
delete_recursive(os.path.join(path, directory.decode('utf-8')), dirs2)
xbmcvfs.rmdir(os.path.join(path, directory.decode('utf-8')))
def unzip(path, dest, folder=None):
''' Unzip file. zipfile module seems to fail on android with badziperror.
'''
path = urllib.quote_plus(path)
root = "zip://" + path + '/'
if folder:
xbmcvfs.mkdir(os.path.join(dest, folder))
dest = os.path.join(dest, folder)
root = get_zip_directory(root, folder)
dirs, files = xbmcvfs.listdir(root)
if dirs:
unzip_recursive(root, dirs, dest)
for file in files:
unzip_file(os.path.join(root, file.decode('utf-8')), os.path.join(dest, file.decode('utf-8')))
LOG.info("Unzipped %s", path)
def unzip_recursive(path, dirs, dest):
for directory in dirs:
dirs_dir = os.path.join(path, directory.decode('utf-8'))
dest_dir = os.path.join(dest, directory.decode('utf-8'))
xbmcvfs.mkdir(dest_dir)
dirs2, files = xbmcvfs.listdir(dirs_dir)
if dirs2:
unzip_recursive(dirs_dir, dirs2, dest_dir)
for file in files:
unzip_file(os.path.join(dirs_dir, file.decode('utf-8')), os.path.join(dest_dir, file.decode('utf-8')))
def unzip_file(path, dest):
''' Unzip specific file. Path should start with zip://
'''
xbmcvfs.copy(path, dest)
LOG.debug("unzip: %s to %s", path, dest)
def get_zip_directory(path, folder):
dirs, files = xbmcvfs.listdir(path)
if folder in dirs:
return os.path.join(path, folder)
for directory in dirs:
result = get_zip_directory(os.path.join(path, directory.decode('utf-8')), folder)
if result:
return result
def copytree(path, dest):
''' Copy folder content from one to another.
'''
dirs, files = xbmcvfs.listdir(path)
if not xbmcvfs.exists(dest):
xbmcvfs.mkdirs(dest)
if dirs:
copy_recursive(path, dirs, dest)
for file in files:
copy_file(os.path.join(path, file.decode('utf-8')), os.path.join(dest, file.decode('utf-8')))
LOG.info("Copied %s", path)
def copy_recursive(path, dirs, dest):
for directory in dirs:
dirs_dir = os.path.join(path, directory.decode('utf-8'))
dest_dir = os.path.join(dest, directory.decode('utf-8'))
xbmcvfs.mkdir(dest_dir)
dirs2, files = xbmcvfs.listdir(dirs_dir)
if dirs2:
copy_recursive(dirs_dir, dirs2, dest_dir)
for file in files:
copy_file(os.path.join(dirs_dir, file.decode('utf-8')), os.path.join(dest_dir, file.decode('utf-8')))
def copy_file(path, dest):
''' Copy specific file.
'''
if path.endswith('.pyo'):
return
xbmcvfs.copy(path, dest)
LOG.debug("copy: %s to %s", path, dest)
def normalize_string(text):
''' For theme media, do not modify unless modified in TV Tunes.
Remove dots from the last character as windows can not have directories
with dots at the end
'''
text = text.replace(":", "")
text = text.replace("/", "-")
text = text.replace("\\", "-")
text = text.replace("<", "")
text = text.replace(">", "")
text = text.replace("*", "")
text = text.replace("?", "")
text = text.replace('|', "")
text = text.strip()
text = text.rstrip('.')
text = unicodedata.normalize('NFKD', unicode(text, 'utf-8')).encode('ascii', 'ignore')
return text
def split_list(itemlist, size):
''' Split up list in pieces of size. Will generate a list of lists
'''
return [itemlist[i:i+size] for i in range(0, len(itemlist), size)]
def convert_to_local(date):
''' Convert the local datetime to local.
'''
from libraries.dateutil import tz, parser
try:
date = parser.parse(date) if type(date) in (unicode, str) else date
date = date.replace(tzinfo=tz.tzutc())
date = date.astimezone(tz.tzlocal())
return date.strftime('%Y-%m-%dT%H:%M:%S')
except Exception as error:
LOG.error(error)
return str(date)

View file

@ -0,0 +1,170 @@
# -*- coding: utf-8 -*-
#################################################################################################
import logging
import xbmcgui
from . import _, LibraryException
from utils import should_stop
#################################################################################################
LOG = logging.getLogger("EMBY."+__name__)
#################################################################################################
def progress(message=None):
''' Will start and close the progress dialog.
'''
def decorator(func):
def wrapper(self, item=None, *args, **kwargs):
dialog = xbmcgui.DialogProgressBG()
if item and type(item) == dict:
dialog.create(_('addon_name'), "%s %s" % (_('gathering'), item['Name']))
LOG.info("Processing %s: %s", item['Name'], item['Id'])
else:
dialog.create(_('addon_name'), message)
LOG.info("Processing %s", message)
if item:
args = (item,) + args
result = func(self, dialog=dialog, *args, **kwargs)
dialog.close()
return result
return wrapper
return decorator
def catch(errors=(Exception,)):
''' Wrapper to catch exceptions and return using catch
'''
def decorator(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except errors as error:
LOG.exception(error)
raise Exception("Caught exception")
return wrapper
return decorator
def silent_catch(errors=(Exception,)):
''' Wrapper to catch exceptions and ignore them
'''
def decorator(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except errors as error:
LOG.error(error)
return wrapper
return decorator
def stop(default=None):
''' Wrapper to catch exceptions and return using catch
'''
def decorator(func):
def wrapper(*args, **kwargs):
try:
if should_stop():
raise Exception
except Exception as error:
if default is not None:
return default
raise LibraryException("StopCalled")
return func(*args, **kwargs)
return wrapper
return decorator
def emby_item():
''' Wrapper to retrieve the emby_db item.
'''
def decorator(func):
def wrapper(self, item, *args, **kwargs):
e_item = self.emby_db.get_item_by_id(item['Id'] if type(item) == dict else item)
return func(self, item, e_item=e_item, *args, **kwargs)
return wrapper
return decorator
def library_check():
''' Wrapper to retrieve the library
'''
def decorator(func):
def wrapper(self, item, *args, **kwargs):
''' TODO: Rethink this one... songs and albums cannot be found by library. expensive.
'''
from database import get_sync
if kwargs.get('library') is None:
sync = get_sync()
if 'e_item' in kwargs:
try:
view_id = kwargs['e_item'][6]
view_name = self.emby_db.get_view_name(view_id)
view = {'Name': view_name, 'Id': view_id}
except Exception:
view = None
if view is None:
ancestors = self.server['api'].get_ancestors(item['Id'])
if not ancestors:
if item['Type'] == 'MusicArtist':
try:
views = self.emby_db.get_views_by_media('music')[0]
except Exception:
return
view = {'Id': views[0], 'Name': views[1]}
else: # Grab the first music library
return
else:
for ancestor in ancestors:
if ancestor['Type'] == 'CollectionFolder':
view = self.emby_db.get_view_name(ancestor['Id'])
view = {'Id': None, 'Name': None} if view is None else {'Name': ancestor['Name'], 'Id': ancestor['Id']}
break
if view['Id'] not in [x.replace('Mixed:', "") for x in sync['Whitelist'] + sync['Libraries']]:
LOG.info("Library %s is not synced. Skip update.", view['Id'])
return
kwargs['library'] = view
return func(self, item, *args, **kwargs)
return wrapper
return decorator

View file

@ -0,0 +1,125 @@
# -*- coding: utf-8 -*-
#################################################################################################
import json
import logging
import os
import xml.etree.ElementTree as etree
import xbmc
from . import _, indent, write_xml, dialog, settings
#################################################################################################
LOG = logging.getLogger("EMBY."+__name__)
#################################################################################################
def sources():
''' Create master lock compatible sources.
Also add the kodi.emby.media source.
'''
path = xbmc.translatePath("special://profile/").decode('utf-8')
file = os.path.join(path, 'sources.xml')
try:
xml = etree.parse(file).getroot()
except Exception:
xml = etree.Element('sources')
video = etree.SubElement(xml, 'video')
files = etree.SubElement(xml, 'files')
etree.SubElement(video, 'default', attrib={'pathversion': "1"})
etree.SubElement(files, 'default', attrib={'pathversion': "1"})
video = xml.find('video')
count = 2
for source in xml.findall('.//path'):
if source.text == 'smb://':
count -= 1
if count == 0:
break
else:
for i in range(0, count):
source = etree.SubElement(video, 'source')
etree.SubElement(source, 'name').text = "Emby"
etree.SubElement(source, 'path', attrib={'pathversion': "1"}).text = "smb://"
etree.SubElement(source, 'allowsharing').text = "true"
try:
files = xml.find('files')
if files is None:
files = etree.SubElement(xml, 'files')
for source in xml.findall('.//path'):
if source.text == 'http://kodi.emby.media':
break
else:
source = etree.SubElement(files, 'source')
etree.SubElement(source, 'name').text = "kodi.emby.media"
etree.SubElement(source, 'path', attrib={'pathversion': "1"}).text = "http://kodi.emby.media"
etree.SubElement(source, 'allowsharing').text = "true"
except Exception as error:
LOG.exception(error)
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), file)
def tvtunes_nfo(path, urls):
''' Create tvtunes.nfo
'''
try:
xml = etree.parse(path).getroot()
except Exception:
xml = etree.Element('tvtunes')
for elem in xml.getiterator('tvtunes'):
for file in list(elem):
elem.remove(file)
for url in urls:
etree.SubElement(xml, 'file').text = url
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), path)
def advanced_settings():
''' Track the existence of <cleanonupdate>true</cleanonupdate>
It is incompatible with plugin paths.
'''
if settings('useDirectPaths') != "0":
return
path = xbmc.translatePath("special://profile/").decode('utf-8')
file = os.path.join(path, 'advancedsettings.xml')
try:
xml = etree.parse(file).getroot()
except Exception:
return
video = xml.find('videolibrary')
if video is not None:
cleanonupdate = video.find('cleanonupdate')
if cleanonupdate is not None and cleanonupdate.text == "true":
LOG.warn("cleanonupdate disabled")
video.remove(cleanonupdate)
indent(xml)
write_xml(etree.tostring(xml, 'UTF-8'), path)
dialog("ok", heading="{emby}", line1=_(33097))
xbmc.executebuiltin('RestartApp')
return True