def checkVersion(self):
        server_info = {}
        activity = {}
        try:
            settings = xbmcaddon.Addon()
            check_version = settings.getSetting('checkVersion') == 'true'
            if check_version == False:
                log.debug("Version Check: Not Enabled")
                return

            path = xbmc.translatePath(settings.getAddonInfo('profile')) + "activity.json"
            f = xbmcvfs.File(path)
            activity_data = f.read()
            f.close()
            activity = json.loads(activity_data)

            if len(activity) == 0:
                log.debug("Version Check: No Activity")
                return

            url = "{server}/emby/system/info/public"
            jsonData = self.downloadUrl(url, suppress=True, authenticate=False)
            server_info = json.loads(jsonData)

        except Exception as error:
            log.debug("Version Check Error: DATA: {0}", error)
            return

        try:
            utcnow = datetime.utcnow()
            today = "%s-%s-%s" % (utcnow.year, utcnow.month, utcnow.day)
            client_info = ClientInformation()
            version_info = {
                "client_id": client_info.getDeviceId(),
                "server_id": server_info.get("Id", ""),
                "version_kodi": xbmc.getInfoLabel('System.BuildVersion'),
                "version_emby": server_info.get("Version", ""),
                "version_addon": client_info.getVersion(),
                "activity": activity,
                "client_utc_date": today
            }
            conn = httplib.HTTPConnection("allthedata.pythonanywhere.com", timeout=15)
            head = {}
            head["Content-Type"] = "application/json"
            postBody = json.dumps(version_info)
            log.debug("Version Check Data: {0}", postBody)
            conn.request(method="POST", url="/version", body=postBody, headers=head)
            data = conn.getresponse()
            if int(data.status) == 200:
                xbmcvfs.delete(path)
                ret_data = data.read()
                log.debug("VERSION_CHECK: RESPONCE: {0}", ret_data)
                message = json.loads(ret_data)
                message_text = message.get("message")
                if message_text is not None and message_text != "OK":
                    xbmcgui.Dialog().ok(self.addon_name, message_text)

        except Exception as error:
            log.debug("Version Check Error: SEND: {0}", error)
def stopAll(played_information):
    if len(played_information) == 0:
        return

    log.debug("played_information: {0}", played_information)

    for item_url in played_information:
        data = played_information.get(item_url)
        if data.get("currently_playing", False) is True:
            log.debug("item_url: {0}", item_url)
            log.debug("item_data: {0}", data)

            current_possition = data.get("currentPossition", 0)
            emby_item_id = data.get("item_id")

            if emby_item_id is not None and len(emby_item_id) != 0 and emby_item_id != "None":
                log.debug("Playback Stopped at: {0}", current_possition)

                url = "{server}/emby/Sessions/Playing/Stopped"
                postdata = {
                    'ItemId': emby_item_id,
                    'MediaSourceId': emby_item_id,
                    'PositionTicks': int(current_possition * 10000000)
                }
                download_utils.downloadUrl(url, postBody=postdata, method="POST")
                data["currently_playing"] = False

                if data.get("play_action_type", "") == "play":
                    promptForStopActions(emby_item_id, current_possition)

    device_id = ClientInformation().getDeviceId()
    url = "{server}/emby/Videos/ActiveEncodings?DeviceId=%s" % device_id
    download_utils.downloadUrl(url, method="DELETE")
示例#3
0
def submit_error_data():

    data = {}

    try:
        error_type, error_short, error_stack, machine_state = format_exception(
        )

        data["error_stack"] = error_stack
        data["error_type"] = error_type
        data["error_short"] = error_short
        data["machine_state"] = machine_state
        data["sys.argv"] = sys.argv
        data["kodi_version"] = xbmc.getInfoLabel("System.BuildVersion")

        client_info = ClientInformation()
        data["addon_version"] = client_info.getVersion()
        data["device_id"] = client_info.getDeviceId()

    except Exception as error:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        stack_trace_data = traceback.format_tb(exc_tb)
        data["report_error"] = str(error)
        data["report_error_stack"] = str(stack_trace_data)

    post_data = json.dumps(data)
    log.debug("ERROR_DATA: {0}", post_data)

    server = "allthedata.pythonanywhere.com"
    url_path = "/submit"
    conn = httplib.HTTPConnection(server, timeout=40)
    head = {}
    head["Content-Type"] = "application/json"
    conn.request(method="POST", url=url_path, body=post_data, headers=head)
    data = conn.getresponse()
    log.debug("Submit Responce Code: {0}", data.status)
示例#4
0
    def getAuthHeader(self, authenticate=True):
        clientInfo = ClientInformation()
        txt_mac = clientInfo.getDeviceId()
        version = clientInfo.getVersion()
        client = clientInfo.getClient()

        settings = xbmcaddon.Addon()
        deviceName = settings.getSetting('deviceName')
        # remove none ascii chars
        deviceName = deviceName.decode("ascii", errors='ignore')
        # remove some chars not valid for names
        deviceName = deviceName.replace("\"", "_")
        if len(deviceName) == 0:
            deviceName = "EmbyCon"

        headers = {}
        headers["Accept-encoding"] = "gzip"
        headers["Accept-Charset"] = "UTF-8,*"

        if (authenticate == False):
            authString = "MediaBrowser Client=\"" + client + "\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
            headers["Authorization"] = authString
            headers['X-Emby-Authorization'] = authString
            return headers
        else:
            userid = self.getUserId()
            authString = "MediaBrowser UserId=\"" + userid + "\",Client=\"" + client + "\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
            headers["Authorization"] = authString
            headers['X-Emby-Authorization'] = authString

            authToken = self.authenticate()
            if (authToken != ""):
                headers["X-MediaBrowser-Token"] = authToken

            log.debug("EmbyCon Authentication Header: {0}", headers)
            return headers
示例#5
0
    def getAuthHeader(self, authenticate=True):
        clientInfo = ClientInformation()
        txt_mac = clientInfo.getDeviceId()
        version = clientInfo.getVersion()
        client = clientInfo.getClient()

        settings = xbmcaddon.Addon()
        deviceName = settings.getSetting('deviceName')
        # remove none ascii chars
        deviceName = deviceName.decode("ascii", errors='ignore')
        # remove some chars not valid for names
        deviceName = deviceName.replace("\"", "_")
        if len(deviceName) == 0:
            deviceName = "EmbyCon"

        headers = {}
        headers["Accept-encoding"] = "gzip"
        headers["Accept-Charset"] = "UTF-8,*"

        if (authenticate == False):
            authString = "MediaBrowser Client=\"" + client + "\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
            headers["Authorization"] = authString
            headers['X-Emby-Authorization'] = authString
            return headers
        else:
            userid = self.getUserId()
            authString = "MediaBrowser UserId=\"" + userid + "\",Client=\"" + client + "\",Device=\"" + deviceName + "\",DeviceId=\"" + txt_mac + "\",Version=\"" + version + "\""
            headers["Authorization"] = authString
            headers['X-Emby-Authorization'] = authString

            authToken = self.authenticate()
            if (authToken != ""):
                headers["X-MediaBrowser-Token"] = authToken

            log.debug("EmbyCon Authentication Header: {0}", headers)
            return headers
示例#6
0
    def getPlayUrl(self, id, media_source, force_transcode, play_session_id):
        log.debug("getPlayUrl")
        addonSettings = xbmcaddon.Addon()
        playback_type = addonSettings.getSetting("playback_type")
        server = downloadUtils.getServer()
        log.debug("playback_type: {0}", playback_type)
        if force_transcode:
            log.debug("playback_type: FORCED_TRANSCODE")
        playurl = None
        log.debug("play_session_id: {0}", play_session_id)
        media_source_id = media_source.get("Id")
        log.debug("media_source_id: {0}", media_source_id)

        is_h265 = False
        streams = media_source.get("MediaStreams", [])
        for stream in streams:
            if stream.get("Type", "") == "Video" and stream.get(
                    "Codec", "") in ["hevc", "h265"]:
                is_h265 = True
                break
        if is_h265:
            log.debug("H265_IS_TRUE")
            h265_action = addonSettings.getSetting("h265_action")
            if h265_action == "1":
                log.debug(
                    "H265 override play action: setting to Direct Streaming")
                playback_type = "1"
            elif h265_action == "2":
                log.debug(
                    "H265 override play action: setting to Transcode Streaming"
                )
                playback_type = "2"

        if force_transcode:
            playback_type = "2"

        # transcode
        if playback_type == "2":

            playback_bitrate = addonSettings.getSetting("playback_bitrate")
            log.debug("playback_bitrate: {0}", playback_bitrate)

            playback_max_width = addonSettings.getSetting("playback_max_width")
            playback_video_force_8 = addonSettings.getSetting(
                "playback_video_force_8") == "true"

            clientInfo = ClientInformation()
            deviceId = clientInfo.getDeviceId()
            bitrate = int(playback_bitrate) * 1000
            user_token = downloadUtils.authenticate()

            playurl = ("%s/emby/Videos/%s/master.m3u8" + "?MediaSourceId=%s" +
                       "&PlaySessionId=%s" + "&VideoCodec=h264" +
                       "&AudioCodec=ac3" + "&MaxAudioChannels=6" +
                       "&deviceId=%s" + "&VideoBitrate=%s" + "&maxWidth=%s")
            playurl = playurl % (server, id, media_source_id, play_session_id,
                                 deviceId, bitrate, playback_max_width)
            if playback_video_force_8:
                playurl = playurl + "&MaxVideoBitDepth=8"
            playurl = playurl + "&api_key=" + user_token

        # do direct path playback
        elif playback_type == "0":
            playurl = media_source.get("Path")

            # handle DVD structure
            if (media_source.get("VideoType") == "Dvd"):
                playurl = playurl + "/VIDEO_TS/VIDEO_TS.IFO"
            elif (media_source.get("VideoType") == "BluRay"):
                playurl = playurl + "/BDMV/index.bdmv"

            smb_username = addonSettings.getSetting('smbusername')
            smb_password = addonSettings.getSetting('smbpassword')

            # add smb creds
            if smb_username == '':
                playurl = playurl.replace("\\\\", "smb://")
            else:
                playurl = playurl.replace(
                    "\\\\", "smb://" + smb_username + ':' + smb_password + '@')

            playurl = playurl.replace("\\", "/")

        # do direct http streaming playback
        elif playback_type == "1":
            playurl = ("%s/emby/Videos/%s/stream" + "?static=true" +
                       "&PlaySessionId=%s" + "&MediaSourceId=%s")
            playurl = playurl % (server, id, play_session_id, media_source_id)
            user_token = downloadUtils.authenticate()
            playurl = playurl + "&api_key=" + user_token

        log.debug("Playback URL: {0}", playurl)
        return playurl, playback_type
示例#7
0
def mainEntryPoint():
    log.debug("===== EmbyCon START =====")

    settings = xbmcaddon.Addon()
    profile_code = settings.getSetting('profile') == "true"
    pr = None
    if (profile_code):
        return_value = xbmcgui.Dialog().yesno("Profiling Enabled", "Do you want to run profiling?")
        if return_value:
            pr = cProfile.Profile()
            pr.enable()

    ADDON_VERSION = ClientInformation().getVersion()
    log.debug("Running Python: {0}", sys.version_info)
    log.debug("Running EmbyCon: {0}", ADDON_VERSION)
    log.debug("Kodi BuildVersion: {0}", xbmc.getInfoLabel("System.BuildVersion"))
    log.debug("Kodi Version: {0}", kodi_version)
    log.debug("Script argument data: {0}", sys.argv)

    try:
        params = get_params(sys.argv[2])
    except:
        params = {}

    home_window = HomeWindow()

    if (len(params) == 0):
        windowParams = home_window.getProperty("Params")
        log.debug("windowParams: {0}", windowParams)
        # home_window.clearProperty("Params")
        if (windowParams):
            try:
                params = get_params(windowParams)
            except:
                params = {}

    log.debug("Script params: {0}", params)

    param_url = params.get('url', None)

    if param_url:
        param_url = urllib.unquote(param_url)

    mode = params.get("mode", None)

    if mode == "CHANGE_USER":
        checkServer(change_user=True, notify=False)
    elif mode== "CACHE_ARTWORK":
        cache_artwork()
    elif mode == "DETECT_SERVER":
        checkServer(force=True, notify=True)
    elif mode == "DETECT_SERVER_USER":
        checkServer(force=True, change_user=True, notify=False)
    elif sys.argv[1] == "markWatched":
        item_id = sys.argv[2]
        markWatched(item_id)
    elif sys.argv[1] == "markUnwatched":
        item_id = sys.argv[2]
        markUnwatched(item_id)
    elif sys.argv[1] == "markFavorite":
        item_id = sys.argv[2]
        markFavorite(item_id)
    elif sys.argv[1] == "unmarkFavorite":
        item_id = sys.argv[2]
        unmarkFavorite(item_id)
    #elif sys.argv[1] == "delete":
    #    item_id = sys.argv[2]
    #    delete(item_id)
    elif mode == "playTrailer":
        item_id = params["id"]
        playTrailer(item_id)
    elif mode == "MOVIE_ALPHA":
        showMovieAlphaList()
    elif mode == "GENRES":
        showGenreList(params)
    elif mode == "MOVIE_PAGES":
        showMoviePages(params)
    elif mode == "MOVIE_YEARS":
        showYearsList()
    elif mode == "WIDGETS":
        showWidgets()
    elif mode == "SHOW_MENU":
        showMenu(params)
    elif mode == "SHOW_SETTINGS":
        __addon__.openSettings()
        WINDOW = xbmcgui.getCurrentWindowId()
        if WINDOW == 10000:
            log.debug("Currently in home - refreshing to allow new settings to be taken")
            xbmc.executebuiltin("ActivateWindow(Home)")
    elif sys.argv[1] == "refresh":
        home_window.setProperty("force_data_reload", "true")
        xbmc.executebuiltin("Container.Refresh")
    elif mode == "WIDGET_CONTENT":
        getWidgetContent(int(sys.argv[1]), params)
    elif mode == "WIDGET_CONTENT_CAST":
        get_widget_content_cast(int(sys.argv[1]), params)
    elif mode == "WIDGET_CONTENT_SIMILAR":
        getWidgetContentSimilar(int(sys.argv[1]), params)
    elif mode == "WIDGET_CONTENT_NEXTUP":
        getWidgetContentNextUp(int(sys.argv[1]), params)
    elif mode == "WIDGET_CONTENT_SUGGESTIONS":
        getSuggestions(int(sys.argv[1]), params)
    elif mode == "WIDGET_CONTENT_URL":
        getWidgetUrlContent(int(sys.argv[1]), params)
    elif mode == "PARENT_CONTENT":
        checkServer(notify=False)
        showParentContent(params)
    elif mode == "SHOW_CONTENT":
        # plugin://plugin.video.embycon?mode=SHOW_CONTENT&item_type=Movie|Series
        checkServer(notify=False)
        showContent(sys.argv[0], int(sys.argv[1]), params)
    elif mode == "SEARCH":
        # plugin://plugin.video.embycon?mode=SEARCH
        checkServer(notify=False)
        xbmcplugin.setContent(int(sys.argv[1]), 'files')
        showSearch()
    elif mode == "NEW_SEARCH":
        checkServer(notify=False)
        searchResults(params)
    elif mode == "SHOW_SERVER_SESSIONS":
        checkServer(notify=False)
        showServerSessions()
    elif mode == "TRAKTTOKODI":
        checkServer(notify=False)
        trakttokodi.entry_point(params)
    else:
        checkServer(notify=False)
        log.debug("EmbyCon -> Mode: {0}", mode)
        log.debug("EmbyCon -> URL: {0}", param_url)

        if mode == "GET_CONTENT":
            getContent(param_url, params)
        elif mode == "PLAY":
            PLAY(params)
        else:
            displaySections()

    dataManager.canRefreshNow = True

    if (pr):
        pr.disable()

        fileTimeStamp = time.strftime("%Y%m%d-%H%M%S")
        tabFileName = __addondir__ + "profile(" + fileTimeStamp + ").txt"
        s = StringIO.StringIO()
        ps = pstats.Stats(pr, stream=s)
        ps = ps.sort_stats('cumulative')
        ps.print_stats()
        ps.strip_dirs()
        ps = ps.sort_stats('tottime')
        ps.print_stats()
        with open(tabFileName, 'wb') as f:
            f.write(s.getvalue())

    log.debug("===== EmbyCon FINISHED =====")
示例#8
0
    def getPlayUrl(self, id, media_source, force_transcode, play_session_id):
        log.debug("getPlayUrl")
        addonSettings = xbmcaddon.Addon()
        playback_type = addonSettings.getSetting("playback_type")
        server = downloadUtils.getServer()
        log.debug("playback_type: {0}", playback_type)
        if force_transcode:
            log.debug("playback_type: FORCED_TRANSCODE")
        playurl = None
        log.debug("play_session_id: {0}", play_session_id)
        media_source_id = media_source.get("Id")
        log.debug("media_source_id: {0}", media_source_id)

        is_h265 = False
        streams = media_source.get("MediaStreams", [])
        for stream in streams:
            if stream.get("Type", "") == "Video" and stream.get("Codec", "") in ["hevc", "h265"]:
                is_h265 = True
                break
        if is_h265:
            log.debug("H265_IS_TRUE")
            h265_action = addonSettings.getSetting("h265_action")
            if h265_action == "1":
                log.debug("H265 override play action: setting to Direct Streaming")
                playback_type = "1"
            elif h265_action == "2":
                log.debug("H265 override play action: setting to Transcode Streaming")
                playback_type = "2"

        if force_transcode:
            playback_type = "2"

        # transcode
        if playback_type == "2":

            playback_bitrate = addonSettings.getSetting("playback_bitrate")
            log.debug("playback_bitrate: {0}", playback_bitrate)

            playback_max_width = addonSettings.getSetting("playback_max_width")
            playback_video_force_8 = addonSettings.getSetting("playback_video_force_8") == "true"

            clientInfo = ClientInformation()
            deviceId = clientInfo.getDeviceId()
            bitrate = int(playback_bitrate) * 1000
            user_token = downloadUtils.authenticate()

            playurl = ("%s/emby/Videos/%s/master.m3u8" +
                       "?MediaSourceId=%s" +
                       "&PlaySessionId=%s" +
                       "&VideoCodec=h264" +
                       "&AudioCodec=ac3" +
                       "&MaxAudioChannels=6" +
                       "&deviceId=%s" +
                       "&VideoBitrate=%s" +
                       "&maxWidth=%s")
            playurl = playurl % (server, id, media_source_id, play_session_id, deviceId, bitrate, playback_max_width)
            if playback_video_force_8:
                playurl = playurl + "&MaxVideoBitDepth=8"
            playurl = playurl + "&api_key=" + user_token

        # do direct path playback
        elif playback_type == "0":
            playurl = media_source.get("Path")

            # handle DVD structure
            if (media_source.get("VideoType") == "Dvd"):
                playurl = playurl + "/VIDEO_TS/VIDEO_TS.IFO"
            elif (media_source.get("VideoType") == "BluRay"):
                playurl = playurl + "/BDMV/index.bdmv"

            smb_username = addonSettings.getSetting('smbusername')
            smb_password = addonSettings.getSetting('smbpassword')

            # add smb creds
            if smb_username == '':
                playurl = playurl.replace("\\\\", "smb://")
            else:
                playurl = playurl.replace("\\\\", "smb://" + smb_username + ':' + smb_password + '@')

            playurl = playurl.replace("\\", "/")

        # do direct http streaming playback
        elif playback_type == "1":
            playurl = ("%s/emby/Videos/%s/stream" +
                       "?static=true" +
                       "&PlaySessionId=%s" +
                       "&MediaSourceId=%s")
            playurl = playurl % (server, id, play_session_id, media_source_id)
            user_token = downloadUtils.authenticate()
            playurl = playurl + "&api_key=" + user_token

        log.debug("Playback URL: {0}", playurl)
        return playurl, playback_type