Prechádzať zdrojové kódy

started work on homepage test buttons

causefx 8 rokov pred
rodič
commit
8c742c40cc

+ 1722 - 1571
api/functions/homepage-connect-functions.php

@@ -2,1638 +2,1789 @@
 
 function homepageConnect($array)
 {
-    switch ($array['data']['action']) {
-        case 'getPlexStreams':
-            return plexConnect('streams');
-            break;
-        case 'getPlexRecent':
-            return plexConnect('recent');
-            break;
-        case 'getPlexMetadata':
-            return plexConnect('metadata', $array['data']['key']);
-            break;
-        case 'getPlexSearch':
-            return plexConnect('search', $array['data']['query']);
-            break;
-        case 'getPlexPlaylists':
-            return getPlexPlaylists();
-            break;
-        case 'getEmbyStreams':
-            return embyConnect('streams');
-            break;
-        case 'getEmbyRecent':
-            return embyConnect('recent');
-            break;
-        case 'getEmbyMetadata':
-            return embyConnect('metadata', $array['data']['key'], true);
-            break;
-        case 'getSabnzbd':
-            return sabnzbdConnect();
-            break;
-        case 'getNzbget':
-            return nzbgetConnect();
-            break;
-        case 'getTransmission':
-            return transmissionConnect();
-            break;
-        case 'getqBittorrent':
-            return qBittorrentConnect();
-            break;
-        case 'getDeluge':
-            return delugeConnect();
-            break;
-        case 'getCalendar':
-            return getCalendar();
-            break;
-        case 'getRequests':
-            return getOmbiRequests();
-            break;
-        default:
-            # code...
-            break;
-    }
-    return false;
+	switch ($array['data']['action']) {
+		case 'getPlexStreams':
+			return plexConnect('streams');
+			break;
+		case 'getPlexRecent':
+			return plexConnect('recent');
+			break;
+		case 'getPlexMetadata':
+			return plexConnect('metadata', $array['data']['key']);
+			break;
+		case 'getPlexSearch':
+			return plexConnect('search', $array['data']['query']);
+			break;
+		case 'getPlexPlaylists':
+			return getPlexPlaylists();
+			break;
+		case 'getEmbyStreams':
+			return embyConnect('streams');
+			break;
+		case 'getEmbyRecent':
+			return embyConnect('recent');
+			break;
+		case 'getEmbyMetadata':
+			return embyConnect('metadata', $array['data']['key'], true);
+			break;
+		case 'getSabnzbd':
+			return sabnzbdConnect();
+			break;
+		case 'getNzbget':
+			return nzbgetConnect();
+			break;
+		case 'getTransmission':
+			return transmissionConnect();
+			break;
+		case 'getqBittorrent':
+			return qBittorrentConnect();
+			break;
+		case 'getDeluge':
+			return delugeConnect();
+			break;
+		case 'getCalendar':
+			return getCalendar();
+			break;
+		case 'getRequests':
+			return getOmbiRequests();
+			break;
+		default:
+			# code...
+			break;
+	}
+	return false;
 }
+
 function streamType($value)
 {
-    if ($value == "transcode" || $value == "Transcode") {
-        return "Transcode";
-    } elseif ($value == "copy" || $value == "DirectStream") {
-        return "Direct Stream";
-    } elseif ($value == "directplay" || $value == "DirectPlay") {
-        return "Direct Play";
-    } else {
-        return "Direct Play";
-    }
+	if ($value == "transcode" || $value == "Transcode") {
+		return "Transcode";
+	} elseif ($value == "copy" || $value == "DirectStream") {
+		return "Direct Stream";
+	} elseif ($value == "directplay" || $value == "DirectPlay") {
+		return "Direct Play";
+	} else {
+		return "Direct Play";
+	}
 }
+
 function resolveEmbyItem($itemDetails)
 {
-    // Grab Each item info from Emby (extra call)
-    $id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
-    $url = qualifyURL($GLOBALS['embyURL']);
-    $url = $url.'/Items?Ids='.$id.'&api_key='.$GLOBALS['embyToken'].'&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
-    try {
-        $options = (localURL($url)) ? array('verify' => false ) : array();
-        $response = Requests::get($url, array(), $options);
-        if ($response->success) {
-            $item = json_decode($response->body, true)['Items'][0];
-        }
-    } catch (Requests_Exception $e) {
-        return false;
-    };
-    // Static Height & Width
-    $height = 300;
-    $width = 200;
-    $nowPlayingHeight = 675;
-    $nowPlayingWidth = 1200;
-    $actorHeight = 450;
-    $actorWidth = 300;
-    // Cache Directories
-    $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-    $cacheDirectoryWeb = 'plugins/images/cache/';
-    // Types
-    $embyItem['array-item'] = $item;
-    $embyItem['array-itemdetails'] = $itemDetails;
-
-    switch (@$item['Type']) {
-        case 'Series':
-            $embyItem['type'] = 'tv';
-            $embyItem['title'] = $item['Name'];
-            $embyItem['summary'] = '';
-            $embyItem['ratingKey'] = $item['Id'];
-            $embyItem['thumb'] = $item['Id'];
-            $embyItem['key'] = $item['Id'] . "-list";
-            $embyItem['nowPlayingThumb'] = $item['Id'];
-            $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
-            $embyItem['metadataKey'] = $item['Id'];
-            $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
-            break;
-        case 'Episode':
-            $embyItem['type'] = 'tv';
-            $embyItem['title'] = $item['SeriesName'];
-            $embyItem['summary'] = '';
-            $embyItem['ratingKey'] = $item['Id'];
-            $embyItem['thumb'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']);
-            $embyItem['key'] = (isset($item['SeriesId'])?$item['SeriesId']:$item['Id']) . "-list";
-            $embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
-            $embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'].'-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'].'-np' : false);
-            $embyItem['metadataKey'] = $item['Id'];
-            $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
-            $embyItem['nowPlayingTitle'] = @$item['SeriesName'].' - '.@$item['Name'];
-            $embyItem['nowPlayingBottom'] = 'S'.@$item['ParentIndexNumber'].' · E'.@$item['IndexNumber'];
-            break;
-        case 'MusicAlbum':
-        case 'Audio':
-            $embyItem['type'] = 'music';
-            $embyItem['title'] = $item['Name'];
-            $embyItem['summary'] = '';
-            $embyItem['ratingKey'] = $item['Id'];
-            $embyItem['thumb'] = $item['Id'];
-            $embyItem['key'] = $item['Id'] . "-list";
-            $embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
-            $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
-            $embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
-            $embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
-            $embyItem['nowPlayingTitle'] = @$item['AlbumArtist'].' - '.@$item['Name'];
-            $embyItem['nowPlayingBottom'] = @$item['Album'];
-            break;
-        case 'Movie':
-            $embyItem['type'] = 'movie';
-            $embyItem['title'] = $item['Name'];
-            $embyItem['summary'] = '';
-            $embyItem['ratingKey'] = $item['Id'];
-            $embyItem['thumb'] = $item['Id'];
-            $embyItem['key'] = $item['Id'] . "-list";
-            $embyItem['nowPlayingThumb'] = $item['Id'];
-            $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
-            $embyItem['metadataKey'] = $item['Id'];
-            $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
-            $embyItem['nowPlayingTitle'] = @$item['Name'];
-            $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
-            break;
-        case 'Video':
-            $embyItem['type'] = 'video';
-            $embyItem['title'] = $item['Name'];
-            $embyItem['summary'] = '';
-            $embyItem['ratingKey'] = $item['Id'];
-            $embyItem['thumb'] = $item['Id'];
-            $embyItem['key'] = $item['Id'] . "-list";
-            $embyItem['nowPlayingThumb'] = $item['Id'];
-            $embyItem['nowPlayingKey'] = $item['Id'] . "-np";
-            $embyItem['metadataKey'] = $item['Id'];
-            $embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
-            $embyItem['nowPlayingTitle'] = @$item['Name'];
-            $embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
-            break;
-        default:
-            return false;
-    }
-    $embyItem['uid'] = $item['Id'];
-    $embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
-    $embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
-    $embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)$item['RunTimeTicks'];
-    $embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
-    $embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
-    $embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
-    $embyItem['id'] = $item['ServerId'];
-    $embyItem['session'] = @$itemDetails['DeviceId'];
-    $embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
-    $embyItem['bandwidthType'] = 'wan';
-    $embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
-    $embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
-    $embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? @(string)$itemDetails['UserName'] : "";
-    $embyItem['userThumb'] = '';
-    $embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
-    $embyItem['address'] = $GLOBALS['embyTabURL'] ? '' : '';
-    $embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'$'.randString();
-    $embyItem['originalImage'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'$'.randString();
-    $embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
-    $embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
-    // Stream info
-    $embyItem['userStream'] = array(
-        'platform' => @(string)$itemDetails['Client'],
-        'product' => @(string)$itemDetails['Client'],
-        'device' => @(string)$itemDetails['DeviceName'],
-        'stream' => @$itemDetails['PlayState']['PlayMethod'],
-        'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
-        'throttled' => false,
-        'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
-        'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
-        'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
-        'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
-        'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
-        'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
-        'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
-        'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
-    );
-    // Genre catch all
-    if ($item['Genres']) {
-        $genres = array();
-        foreach ($item['Genres'] as $genre) {
-            $genres[] = $genre;
-        }
-    }
-    // Actor catch all
-    if ($item['People']) {
-        $actors = array();
-        foreach ($item['People'] as $key => $value) {
-            if (@$value['PrimaryImageTag'] && @$value['Role']) {
-                if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')) {
-                    $actorImage = $cacheDirectoryWeb.(string)$value['Id'].'-cast.jpg';
-                }
-                if (file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg') && (time() - 604800) > filemtime($cacheDirectory.(string)$value['Id'].'-cast.jpg') || !file_exists($cacheDirectory.(string)$value['Id'].'-cast.jpg')) {
-                    $actorImage = 'api/?v1/image&source=emby&type=Primary&img='.(string)$value['Id'].'&height='.$actorHeight.'&width='.$actorWidth.'&key='.(string)$value['Id'].'-cast';
-                }
-                $actors[] = array(
-                    'name' =>  (string)$value['Name'],
-                    'role' =>  (string)$value['Role'],
-                    'thumb' =>  $actorImage
-                );
-            }
-        }
-    }
-    // Metadata information
-    $embyItem['metadata'] = array(
-        'guid' => $item['Id'],
-        'summary' => @(string)$item['Overview'],
-        'rating' => @(string)$item['CommunityRating'],
-        'duration' => @(string)$item['RunTimeTicks'],
-        'originallyAvailableAt' => @(string)$item['PremiereDate'],
-        'year' => (string)$item['ProductionYear'],
-        //'studio' => (string)$item['studio'],
-        'tagline' => @(string)$item['Taglines'][0],
-        'genres' => ($item['Genres']) ?  $genres : '',
-        'actors' => ($item['People']) ?  $actors : ''
-    );
-
-    if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
-        $embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$embyItem['nowPlayingKey'].'.jpg';
-    }
-    if (file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
-        $embyItem['imageURL']  = $cacheDirectoryWeb.$embyItem['key'].'.jpg';
-    }
-    if (file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$embyItem['nowPlayingKey'].'.jpg')) {
-        $embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['nowPlayingImageType'].'&img='.$embyItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$embyItem['nowPlayingKey'].'';
-    }
-    if (file_exists($cacheDirectory.$embyItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$embyItem['key'].'.jpg') || !file_exists($cacheDirectory.$embyItem['key'].'.jpg')) {
-        $embyItem['imageURL'] = 'api/?v1/image&source=emby&type='.$embyItem['imageType'].'&img='.$embyItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$embyItem['key'].'';
-    }
-    if (!$embyItem['nowPlayingThumb']) {
-        $embyItem['nowPlayingOriginalImage']  = $embyItem['nowPlayingImageURL']  = "plugins/images/cache/no-np.png";
-        $embyItem['nowPlayingKey'] = "no-np";
-    }
-    if (!$embyItem['thumb']) {
-        $embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png";
-        $embyItem['key'] = "no-list";
-    }
-    if (isset($useImage)) {
-        $embyItem['useImage'] = $useImage;
-    }
-    return $embyItem;
+	// Grab Each item info from Emby (extra call)
+	$id = isset($itemDetails['NowPlayingItem']['Id']) ? $itemDetails['NowPlayingItem']['Id'] : $itemDetails['Id'];
+	$url = qualifyURL($GLOBALS['embyURL']);
+	$url = $url . '/Items?Ids=' . $id . '&api_key=' . $GLOBALS['embyToken'] . '&Fields=Overview,People,Genres,CriticRating,Studios,Taglines';
+	try {
+		$options = (localURL($url)) ? array('verify' => false) : array();
+		$response = Requests::get($url, array(), $options);
+		if ($response->success) {
+			$item = json_decode($response->body, true)['Items'][0];
+		}
+	} catch (Requests_Exception $e) {
+		return false;
+	};
+	// Static Height & Width
+	$height = 300;
+	$width = 200;
+	$nowPlayingHeight = 675;
+	$nowPlayingWidth = 1200;
+	$actorHeight = 450;
+	$actorWidth = 300;
+	// Cache Directories
+	$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+	$cacheDirectoryWeb = 'plugins/images/cache/';
+	// Types
+	$embyItem['array-item'] = $item;
+	$embyItem['array-itemdetails'] = $itemDetails;
+	
+	switch (@$item['Type']) {
+		case 'Series':
+			$embyItem['type'] = 'tv';
+			$embyItem['title'] = $item['Name'];
+			$embyItem['summary'] = '';
+			$embyItem['ratingKey'] = $item['Id'];
+			$embyItem['thumb'] = $item['Id'];
+			$embyItem['key'] = $item['Id'] . "-list";
+			$embyItem['nowPlayingThumb'] = $item['Id'];
+			$embyItem['nowPlayingKey'] = $item['Id'] . "-np";
+			$embyItem['metadataKey'] = $item['Id'];
+			$embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['BackdropImageTags'][0]) ? 'Backdrop' : '');
+			break;
+		case 'Episode':
+			$embyItem['type'] = 'tv';
+			$embyItem['title'] = $item['SeriesName'];
+			$embyItem['summary'] = '';
+			$embyItem['ratingKey'] = $item['Id'];
+			$embyItem['thumb'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']);
+			$embyItem['key'] = (isset($item['SeriesId']) ? $item['SeriesId'] : $item['Id']) . "-list";
+			$embyItem['nowPlayingThumb'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] : false);
+			$embyItem['nowPlayingKey'] = isset($item['ParentThumbItemId']) ? $item['ParentThumbItemId'] . '-np' : (isset($item['ParentBackdropItemId']) ? $item['ParentBackdropItemId'] . '-np' : false);
+			$embyItem['metadataKey'] = $item['Id'];
+			$embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? 'Thumb' : (isset($item['ParentBackdropImageTags'][0]) ? 'Backdrop' : '');
+			$embyItem['nowPlayingTitle'] = @$item['SeriesName'] . ' - ' . @$item['Name'];
+			$embyItem['nowPlayingBottom'] = 'S' . @$item['ParentIndexNumber'] . ' · E' . @$item['IndexNumber'];
+			break;
+		case 'MusicAlbum':
+		case 'Audio':
+			$embyItem['type'] = 'music';
+			$embyItem['title'] = $item['Name'];
+			$embyItem['summary'] = '';
+			$embyItem['ratingKey'] = $item['Id'];
+			$embyItem['thumb'] = $item['Id'];
+			$embyItem['key'] = $item['Id'] . "-list";
+			$embyItem['nowPlayingThumb'] = (isset($item['AlbumId']) ? $item['AlbumId'] : @$item['ParentBackdropItemId']);
+			$embyItem['nowPlayingKey'] = $item['Id'] . "-np";
+			$embyItem['metadataKey'] = isset($item['AlbumId']) ? $item['AlbumId'] : $item['Id'];
+			$embyItem['nowPlayingImageType'] = (isset($item['ParentBackdropItemId']) ? "Primary" : "Backdrop");
+			$embyItem['nowPlayingTitle'] = @$item['AlbumArtist'] . ' - ' . @$item['Name'];
+			$embyItem['nowPlayingBottom'] = @$item['Album'];
+			break;
+		case 'Movie':
+			$embyItem['type'] = 'movie';
+			$embyItem['title'] = $item['Name'];
+			$embyItem['summary'] = '';
+			$embyItem['ratingKey'] = $item['Id'];
+			$embyItem['thumb'] = $item['Id'];
+			$embyItem['key'] = $item['Id'] . "-list";
+			$embyItem['nowPlayingThumb'] = $item['Id'];
+			$embyItem['nowPlayingKey'] = $item['Id'] . "-np";
+			$embyItem['metadataKey'] = $item['Id'];
+			$embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
+			$embyItem['nowPlayingTitle'] = @$item['Name'];
+			$embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
+			break;
+		case 'Video':
+			$embyItem['type'] = 'video';
+			$embyItem['title'] = $item['Name'];
+			$embyItem['summary'] = '';
+			$embyItem['ratingKey'] = $item['Id'];
+			$embyItem['thumb'] = $item['Id'];
+			$embyItem['key'] = $item['Id'] . "-list";
+			$embyItem['nowPlayingThumb'] = $item['Id'];
+			$embyItem['nowPlayingKey'] = $item['Id'] . "-np";
+			$embyItem['metadataKey'] = $item['Id'];
+			$embyItem['nowPlayingImageType'] = isset($item['ImageTags']['Thumb']) ? "Thumb" : (isset($item['BackdropImageTags']) ? "Backdrop" : false);
+			$embyItem['nowPlayingTitle'] = @$item['Name'];
+			$embyItem['nowPlayingBottom'] = @$item['ProductionYear'];
+			break;
+		default:
+			return false;
+	}
+	$embyItem['uid'] = $item['Id'];
+	$embyItem['imageType'] = (isset($item['ImageTags']['Primary']) ? "Primary" : false);
+	$embyItem['elapsed'] = isset($itemDetails['PlayState']['PositionTicks']) && $itemDetails['PlayState']['PositionTicks'] !== '0' ? (int)$itemDetails['PlayState']['PositionTicks'] : null;
+	$embyItem['duration'] = isset($itemDetails['NowPlayingItem']['RunTimeTicks']) ? (int)$itemDetails['NowPlayingItem']['RunTimeTicks'] : (int)$item['RunTimeTicks'];
+	$embyItem['watched'] = ($embyItem['elapsed'] && $embyItem['duration'] ? floor(($embyItem['elapsed'] / $embyItem['duration']) * 100) : 0);
+	$embyItem['transcoded'] = isset($itemDetails['TranscodingInfo']['CompletionPercentage']) ? floor((int)$itemDetails['TranscodingInfo']['CompletionPercentage']) : 100;
+	$embyItem['stream'] = @$itemDetails['PlayState']['PlayMethod'];
+	$embyItem['id'] = $item['ServerId'];
+	$embyItem['session'] = @$itemDetails['DeviceId'];
+	$embyItem['bandwidth'] = isset($itemDetails['TranscodingInfo']['Bitrate']) ? $itemDetails['TranscodingInfo']['Bitrate'] / 1000 : '';
+	$embyItem['bandwidthType'] = 'wan';
+	$embyItem['sessionType'] = (@$itemDetails['PlayState']['PlayMethod'] == 'Transcode') ? 'Transcoding' : 'Direct Playing';
+	$embyItem['state'] = ((@(string)$itemDetails['PlayState']['IsPaused'] == '1') ? "pause" : "play");
+	$embyItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? @(string)$itemDetails['UserName'] : "";
+	$embyItem['userThumb'] = '';
+	$embyItem['userAddress'] = (isset($itemDetails['RemoteEndPoint']) ? $itemDetails['RemoteEndPoint'] : "x.x.x.x");
+	$embyItem['address'] = $GLOBALS['embyTabURL'] ? '' : '';
+	$embyItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '$' . randString();
+	$embyItem['originalImage'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '$' . randString();
+	$embyItem['openTab'] = $GLOBALS['embyTabURL'] && $GLOBALS['embyTabName'] ? true : false;
+	$embyItem['tabName'] = $GLOBALS['embyTabName'] ? $GLOBALS['embyTabName'] : '';
+	// Stream info
+	$embyItem['userStream'] = array(
+		'platform' => @(string)$itemDetails['Client'],
+		'product' => @(string)$itemDetails['Client'],
+		'device' => @(string)$itemDetails['DeviceName'],
+		'stream' => @$itemDetails['PlayState']['PlayMethod'],
+		'videoResolution' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]['Width']) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Width'] : '',
+		'throttled' => false,
+		'sourceVideoCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : '',
+		'videoCodec' => @$itemDetails['TranscodingInfo']['VideoCodec'],
+		'audioCodec' => @$itemDetails['TranscodingInfo']['AudioCodec'],
+		'sourceAudioCodec' => isset($itemDetails['NowPlayingItem']['MediaStreams'][1]) ? $itemDetails['NowPlayingItem']['MediaStreams'][1]['Codec'] : (isset($itemDetails['NowPlayingItem']['MediaStreams'][0]) ? $itemDetails['NowPlayingItem']['MediaStreams'][0]['Codec'] : ''),
+		'videoDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
+		'audioDecision' => streamType(@$itemDetails['PlayState']['PlayMethod']),
+		'container' => isset($itemDetails['NowPlayingItem']['Container']) ? $itemDetails['NowPlayingItem']['Container'] : '',
+		'audioChannels' => @$itemDetails['TranscodingInfo']['AudioChannels']
+	);
+	// Genre catch all
+	if ($item['Genres']) {
+		$genres = array();
+		foreach ($item['Genres'] as $genre) {
+			$genres[] = $genre;
+		}
+	}
+	// Actor catch all
+	if ($item['People']) {
+		$actors = array();
+		foreach ($item['People'] as $key => $value) {
+			if (@$value['PrimaryImageTag'] && @$value['Role']) {
+				if (file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg')) {
+					$actorImage = $cacheDirectoryWeb . (string)$value['Id'] . '-cast.jpg';
+				}
+				if (file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg') && (time() - 604800) > filemtime($cacheDirectory . (string)$value['Id'] . '-cast.jpg') || !file_exists($cacheDirectory . (string)$value['Id'] . '-cast.jpg')) {
+					$actorImage = 'api/?v1/image&source=emby&type=Primary&img=' . (string)$value['Id'] . '&height=' . $actorHeight . '&width=' . $actorWidth . '&key=' . (string)$value['Id'] . '-cast';
+				}
+				$actors[] = array(
+					'name' => (string)$value['Name'],
+					'role' => (string)$value['Role'],
+					'thumb' => $actorImage
+				);
+			}
+		}
+	}
+	// Metadata information
+	$embyItem['metadata'] = array(
+		'guid' => $item['Id'],
+		'summary' => @(string)$item['Overview'],
+		'rating' => @(string)$item['CommunityRating'],
+		'duration' => @(string)$item['RunTimeTicks'],
+		'originallyAvailableAt' => @(string)$item['PremiereDate'],
+		'year' => (string)$item['ProductionYear'],
+		//'studio' => (string)$item['studio'],
+		'tagline' => @(string)$item['Taglines'][0],
+		'genres' => ($item['Genres']) ? $genres : '',
+		'actors' => ($item['People']) ? $actors : ''
+	);
+	
+	if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
+		$embyItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $embyItem['nowPlayingKey'] . '.jpg';
+	}
+	if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
+		$embyItem['imageURL'] = $cacheDirectoryWeb . $embyItem['key'] . '.jpg';
+	}
+	if (file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['nowPlayingKey'] . '.jpg')) {
+		$embyItem['nowPlayingImageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['nowPlayingImageType'] . '&img=' . $embyItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $embyItem['nowPlayingKey'] . '';
+	}
+	if (file_exists($cacheDirectory . $embyItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $embyItem['key'] . '.jpg') || !file_exists($cacheDirectory . $embyItem['key'] . '.jpg')) {
+		$embyItem['imageURL'] = 'api/?v1/image&source=emby&type=' . $embyItem['imageType'] . '&img=' . $embyItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $embyItem['key'] . '';
+	}
+	if (!$embyItem['nowPlayingThumb']) {
+		$embyItem['nowPlayingOriginalImage'] = $embyItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
+		$embyItem['nowPlayingKey'] = "no-np";
+	}
+	if (!$embyItem['thumb']) {
+		$embyItem['originalImage'] = $embyItem['imageURL'] = "plugins/images/cache/no-list.png";
+		$embyItem['key'] = "no-list";
+	}
+	if (isset($useImage)) {
+		$embyItem['useImage'] = $useImage;
+	}
+	return $embyItem;
 }
+
 function resolvePlexItem($item)
 {
-    // Static Height & Width
-    $height = 300;
-    $width = 200;
-    $nowPlayingHeight = 675;
-    $nowPlayingWidth = 1200;
-    // Cache Directories
-    $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-    $cacheDirectoryWeb = 'plugins/images/cache/';
-    // Types
-    switch ($item['type']) {
-        case 'season':
-            $plexItem['type'] = 'tv';
-            $plexItem['title'] = (string)$item['parentTitle'];
-            $plexItem['summary'] = (string)$item['parentSummary'];
-            $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
-            $plexItem['thumb'] = (string)$item['thumb'];
-            $plexItem['key'] = (string)$item['ratingKey'] . "-list";
-            $plexItem['nowPlayingThumb'] = (string)$item['art'];
-            $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
-            $plexItem['metadataKey'] = (string)$item['parentRatingKey'];
-            break;
-        case 'episode':
-            $plexItem['type'] = 'tv';
-            $plexItem['title'] = (string)$item['grandparentTitle'];
-            $plexItem['summary'] = (string)$item['title'];
-            $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
-            $plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
-            $plexItem['key'] = (string)$item['ratingKey'] . "-list";
-            $plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
-            $plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
-            $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
-            $plexItem['nowPlayingBottom'] = 'S'.(string)$item['parentIndex'].' · E'.(string)$item['index'];
-            $plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
-            break;
-        case 'clip':
-            $useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
-            $plexItem['type'] = 'clip';
-            $plexItem['title'] = (string)$item['title'];
-            $plexItem['summary'] = (string)$item['summary'];
-            $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
-            $plexItem['thumb'] = (string)$item['thumb'];
-            $plexItem['key'] = (string)$item['ratingKey'] . "-list";
-            $plexItem['nowPlayingThumb'] = (string)$item['art'];
-            $plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
-            $plexItem['nowPlayingTitle'] = $plexItem['title'];
-            $plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
-            break;
-        case 'album':
-        case 'track':
-            $plexItem['type'] = 'music';
-            $plexItem['title'] = (string)$item['parentTitle'].' - '.(string)$item['title'];
-            $plexItem['summary'] = (string)$item['title'];
-            $plexItem['ratingKey'] = (string)$item['parentRatingKey'];
-            $plexItem['thumb'] = (string)$item['thumb'];
-            $plexItem['key'] = (string)$item['ratingKey'] . "-list";
-            $plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] :  (string)$item['art'];
-            $plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
-            $plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'].' - '.(string)$item['title'];
-            $plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
-            $plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
-            break;
-        default:
-            $plexItem['type'] = 'movie';
-            $plexItem['title'] = (string)$item['title'];
-            $plexItem['summary'] = (string)$item['summary'];
-            $plexItem['ratingKey'] = (string)$item['ratingKey'];
-            $plexItem['thumb'] = (string)$item['thumb'];
-            $plexItem['key'] = (string)$item['ratingKey'] . "-list";
-            $plexItem['nowPlayingThumb'] = (string)$item['art'];
-            $plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
-            $plexItem['nowPlayingTitle'] = (string)$item['title'];
-            $plexItem['nowPlayingBottom'] = (string)$item['year'];
-            $plexItem['metadataKey'] = (string)$item['ratingKey'];
-    }
-    $plexItem['uid'] = (string)$item['ratingKey'];
-    $plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
-    $plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
-    $plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
-    $plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress']- $plexItem['watched']) : '';
-    $plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision']: '';
-    $plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
-    $plexItem['session'] = (string)$item->Session['id'];
-    $plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
-    $plexItem['bandwidthType'] = (string)$item->Session['location'];
-    $plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
-    $plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
-    $plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
-    $plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
-    $plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
-    $plexItem['address'] = $GLOBALS['plexTabURL'] ? $GLOBALS['plexTabURL']."/web/index.html#!/server/".$GLOBALS['plexID']."/details?key=/library/metadata/".$item['ratingKey'] : "https://app.plex.tv/web/app#!/server/".$GLOBALS['plexID']."/details?key=/library/metadata/".$item['ratingKey'];
-    $plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'$'.randString();
-    $plexItem['originalImage'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'$'.randString();
-    $plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
-    $plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
-    // Stream info
-    $plexItem['userStream'] = array(
-        'platform' => (string)$item->Player['platform'],
-        'product' => (string)$item->Player['product'],
-        'device' => (string)$item->Player['device'],
-        'stream' => (string)$item->Media->Part['decision'].($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)': ''),
-        'videoResolution' => (string)$item->Media['videoResolution'],
-        'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
-        'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
-        'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
-        'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
-        'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
-        'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
-        'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
-        'container' => (string)$item->TranscodeSession['container'],
-        'audioChannels' => (string)$item->TranscodeSession['audioChannels']
-    );
-    // Genre catch all
-    if ($item->Genre) {
-        $genres = array();
-        foreach ($item->Genre as $key => $value) {
-            $genres[] = (string)$value['tag'];
-        }
-    }
-    // Actor catch all
-    if ($item->Role) {
-        $actors = array();
-        foreach ($item->Role  as $key => $value) {
-            if ($value['thumb']) {
-                $actors[] = array(
-                    'name' =>  (string)$value['tag'],
-                    'role' =>  (string)$value['role'],
-                    'thumb' =>  (string)$value['thumb']
-                );
-            }
-        }
-    }
-    // Metadata information
-    $plexItem['metadata'] = array(
-        'guid' => (string)$item['guid'],
-        'summary' => (string)$item['summary'],
-        'rating' => (string)$item['rating'],
-        'duration' => (string)$item['duration'],
-        'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
-        'year' => (string)$item['year'],
-        'studio' => (string)$item['studio'],
-        'tagline' => (string)$item['tagline'],
-        'genres' => ($item->Genre) ?  $genres : '',
-        'actors' => ($item->Role) ?  $actors : ''
-    );
-    if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
-        $plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb.$plexItem['nowPlayingKey'].'.jpg';
-    }
-    if (file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
-        $plexItem['imageURL']  = $cacheDirectoryWeb.$plexItem['key'].'.jpg';
-    }
-    if (file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg') || !file_exists($cacheDirectory.$plexItem['nowPlayingKey'].'.jpg')) {
-        $plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['nowPlayingThumb'].'&height='.$nowPlayingHeight.'&width='.$nowPlayingWidth.'&key='.$plexItem['nowPlayingKey'].'';
-    }
-    if (file_exists($cacheDirectory.$plexItem['key'].'.jpg') && (time() - 604800) > filemtime($cacheDirectory.$plexItem['key'].'.jpg') || !file_exists($cacheDirectory.$plexItem['key'].'.jpg')) {
-        $plexItem['imageURL'] = 'api/?v1/image&source=plex&img='.$plexItem['thumb'].'&height='.$height.'&width='.$width.'&key='.$plexItem['key'].'';
-    }
-    if (!$plexItem['nowPlayingThumb']) {
-        $plexItem['nowPlayingOriginalImage']  = $plexItem['nowPlayingImageURL']  = "plugins/images/cache/no-np.png";
-        $plexItem['nowPlayingKey'] = "no-np";
-    }
-    if (!$plexItem['thumb']) {
-        $plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
-        $plexItem['key'] = "no-list";
-    }
-    if (isset($useImage)) {
-        $plexItem['useImage'] = $useImage;
-    }
-    return $plexItem;
+	// Static Height & Width
+	$height = 300;
+	$width = 200;
+	$nowPlayingHeight = 675;
+	$nowPlayingWidth = 1200;
+	// Cache Directories
+	$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+	$cacheDirectoryWeb = 'plugins/images/cache/';
+	// Types
+	switch ($item['type']) {
+		case 'season':
+			$plexItem['type'] = 'tv';
+			$plexItem['title'] = (string)$item['parentTitle'];
+			$plexItem['summary'] = (string)$item['parentSummary'];
+			$plexItem['ratingKey'] = (string)$item['parentRatingKey'];
+			$plexItem['thumb'] = (string)$item['thumb'];
+			$plexItem['key'] = (string)$item['ratingKey'] . "-list";
+			$plexItem['nowPlayingThumb'] = (string)$item['art'];
+			$plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
+			$plexItem['metadataKey'] = (string)$item['parentRatingKey'];
+			break;
+		case 'episode':
+			$plexItem['type'] = 'tv';
+			$plexItem['title'] = (string)$item['grandparentTitle'];
+			$plexItem['summary'] = (string)$item['title'];
+			$plexItem['ratingKey'] = (string)$item['parentRatingKey'];
+			$plexItem['thumb'] = ($item['parentThumb'] ? (string)$item['parentThumb'] : (string)$item['grandparentThumb']);
+			$plexItem['key'] = (string)$item['ratingKey'] . "-list";
+			$plexItem['nowPlayingThumb'] = (string)$item['grandparentArt'];
+			$plexItem['nowPlayingKey'] = (string)$item['grandparentRatingKey'] . "-np";
+			$plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
+			$plexItem['nowPlayingBottom'] = 'S' . (string)$item['parentIndex'] . ' · E' . (string)$item['index'];
+			$plexItem['metadataKey'] = (string)$item['grandparentRatingKey'];
+			break;
+		case 'clip':
+			$useImage = (isset($item['live']) ? "plugins/images/cache/livetv.png" : null);
+			$plexItem['type'] = 'clip';
+			$plexItem['title'] = (string)$item['title'];
+			$plexItem['summary'] = (string)$item['summary'];
+			$plexItem['ratingKey'] = (string)$item['parentRatingKey'];
+			$plexItem['thumb'] = (string)$item['thumb'];
+			$plexItem['key'] = (string)$item['ratingKey'] . "-list";
+			$plexItem['nowPlayingThumb'] = (string)$item['art'];
+			$plexItem['nowPlayingKey'] = isset($item['ratingKey']) ? (string)$item['ratingKey'] . "-np" : (isset($item['live']) ? "livetv.png" : ":)");
+			$plexItem['nowPlayingTitle'] = $plexItem['title'];
+			$plexItem['nowPlayingBottom'] = isset($item['extraType']) ? "Trailer" : (isset($item['live']) ? "Live TV" : ":)");
+			break;
+		case 'album':
+		case 'track':
+			$plexItem['type'] = 'music';
+			$plexItem['title'] = (string)$item['parentTitle'] . ' - ' . (string)$item['title'];
+			$plexItem['summary'] = (string)$item['title'];
+			$plexItem['ratingKey'] = (string)$item['parentRatingKey'];
+			$plexItem['thumb'] = (string)$item['thumb'];
+			$plexItem['key'] = (string)$item['ratingKey'] . "-list";
+			$plexItem['nowPlayingThumb'] = ($item['parentThumb']) ? (string)$item['parentThumb'] : (string)$item['art'];
+			$plexItem['nowPlayingKey'] = (string)$item['parentRatingKey'] . "-np";
+			$plexItem['nowPlayingTitle'] = (string)$item['grandparentTitle'] . ' - ' . (string)$item['title'];
+			$plexItem['nowPlayingBottom'] = (string)$item['parentTitle'];
+			$plexItem['metadataKey'] = isset($item['grandparentRatingKey']) ? (string)$item['grandparentRatingKey'] : (string)$item['parentRatingKey'];
+			break;
+		default:
+			$plexItem['type'] = 'movie';
+			$plexItem['title'] = (string)$item['title'];
+			$plexItem['summary'] = (string)$item['summary'];
+			$plexItem['ratingKey'] = (string)$item['ratingKey'];
+			$plexItem['thumb'] = (string)$item['thumb'];
+			$plexItem['key'] = (string)$item['ratingKey'] . "-list";
+			$plexItem['nowPlayingThumb'] = (string)$item['art'];
+			$plexItem['nowPlayingKey'] = (string)$item['ratingKey'] . "-np";
+			$plexItem['nowPlayingTitle'] = (string)$item['title'];
+			$plexItem['nowPlayingBottom'] = (string)$item['year'];
+			$plexItem['metadataKey'] = (string)$item['ratingKey'];
+	}
+	$plexItem['uid'] = (string)$item['ratingKey'];
+	$plexItem['elapsed'] = isset($item['viewOffset']) && $item['viewOffset'] !== '0' ? (int)$item['viewOffset'] : null;
+	$plexItem['duration'] = isset($item['duration']) ? (int)$item['duration'] : (int)$item->Media['duration'];
+	$plexItem['watched'] = ($plexItem['elapsed'] && $plexItem['duration'] ? floor(($plexItem['elapsed'] / $plexItem['duration']) * 100) : 0);
+	$plexItem['transcoded'] = isset($item->TranscodeSession['progress']) ? floor((int)$item->TranscodeSession['progress'] - $plexItem['watched']) : '';
+	$plexItem['stream'] = isset($item->Media->Part->Stream['decision']) ? (string)$item->Media->Part->Stream['decision'] : '';
+	$plexItem['id'] = str_replace('"', '', (string)$item->Player['machineIdentifier']);
+	$plexItem['session'] = (string)$item->Session['id'];
+	$plexItem['bandwidth'] = (string)$item->Session['bandwidth'];
+	$plexItem['bandwidthType'] = (string)$item->Session['location'];
+	$plexItem['sessionType'] = isset($item->TranscodeSession['progress']) ? 'Transcoding' : 'Direct Playing';
+	$plexItem['state'] = (((string)$item->Player['state'] == "paused") ? "pause" : "play");
+	$plexItem['user'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['title'] : "";
+	$plexItem['userThumb'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->User['thumb'] : "";
+	$plexItem['userAddress'] = ($GLOBALS['homepageShowStreamNames'] && qualifyRequest($GLOBALS['homepageShowStreamNamesAuth'])) ? (string)$item->Player['address'] : "x.x.x.x";
+	$plexItem['address'] = $GLOBALS['plexTabURL'] ? $GLOBALS['plexTabURL'] . "/web/index.html#!/server/" . $GLOBALS['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'] : "https://app.plex.tv/web/app#!/server/" . $GLOBALS['plexID'] . "/details?key=/library/metadata/" . $item['ratingKey'];
+	$plexItem['nowPlayingOriginalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '$' . randString();
+	$plexItem['originalImage'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '$' . randString();
+	$plexItem['openTab'] = $GLOBALS['plexTabURL'] && $GLOBALS['plexTabName'] ? true : false;
+	$plexItem['tabName'] = $GLOBALS['plexTabName'] ? $GLOBALS['plexTabName'] : '';
+	// Stream info
+	$plexItem['userStream'] = array(
+		'platform' => (string)$item->Player['platform'],
+		'product' => (string)$item->Player['product'],
+		'device' => (string)$item->Player['device'],
+		'stream' => (string)$item->Media->Part['decision'] . ($item->TranscodeSession['throttled'] == '1' ? ' (Throttled)' : ''),
+		'videoResolution' => (string)$item->Media['videoResolution'],
+		'throttled' => ($item->TranscodeSession['throttled'] == 1) ? true : false,
+		'sourceVideoCodec' => (string)$item->TranscodeSession['sourceVideoCodec'],
+		'videoCodec' => (string)$item->TranscodeSession['videoCodec'],
+		'audioCodec' => (string)$item->TranscodeSession['audioCodec'],
+		'sourceAudioCodec' => (string)$item->TranscodeSession['sourceAudioCodec'],
+		'videoDecision' => streamType((string)$item->TranscodeSession['videoDecision']),
+		'audioDecision' => streamType((string)$item->TranscodeSession['audioDecision']),
+		'container' => (string)$item->TranscodeSession['container'],
+		'audioChannels' => (string)$item->TranscodeSession['audioChannels']
+	);
+	// Genre catch all
+	if ($item->Genre) {
+		$genres = array();
+		foreach ($item->Genre as $key => $value) {
+			$genres[] = (string)$value['tag'];
+		}
+	}
+	// Actor catch all
+	if ($item->Role) {
+		$actors = array();
+		foreach ($item->Role as $key => $value) {
+			if ($value['thumb']) {
+				$actors[] = array(
+					'name' => (string)$value['tag'],
+					'role' => (string)$value['role'],
+					'thumb' => (string)$value['thumb']
+				);
+			}
+		}
+	}
+	// Metadata information
+	$plexItem['metadata'] = array(
+		'guid' => (string)$item['guid'],
+		'summary' => (string)$item['summary'],
+		'rating' => (string)$item['rating'],
+		'duration' => (string)$item['duration'],
+		'originallyAvailableAt' => (string)$item['originallyAvailableAt'],
+		'year' => (string)$item['year'],
+		'studio' => (string)$item['studio'],
+		'tagline' => (string)$item['tagline'],
+		'genres' => ($item->Genre) ? $genres : '',
+		'actors' => ($item->Role) ? $actors : ''
+	);
+	if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
+		$plexItem['nowPlayingImageURL'] = $cacheDirectoryWeb . $plexItem['nowPlayingKey'] . '.jpg';
+	}
+	if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
+		$plexItem['imageURL'] = $cacheDirectoryWeb . $plexItem['key'] . '.jpg';
+	}
+	if (file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['nowPlayingKey'] . '.jpg')) {
+		$plexItem['nowPlayingImageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['nowPlayingThumb'] . '&height=' . $nowPlayingHeight . '&width=' . $nowPlayingWidth . '&key=' . $plexItem['nowPlayingKey'] . '';
+	}
+	if (file_exists($cacheDirectory . $plexItem['key'] . '.jpg') && (time() - 604800) > filemtime($cacheDirectory . $plexItem['key'] . '.jpg') || !file_exists($cacheDirectory . $plexItem['key'] . '.jpg')) {
+		$plexItem['imageURL'] = 'api/?v1/image&source=plex&img=' . $plexItem['thumb'] . '&height=' . $height . '&width=' . $width . '&key=' . $plexItem['key'] . '';
+	}
+	if (!$plexItem['nowPlayingThumb']) {
+		$plexItem['nowPlayingOriginalImage'] = $plexItem['nowPlayingImageURL'] = "plugins/images/cache/no-np.png";
+		$plexItem['nowPlayingKey'] = "no-np";
+	}
+	if (!$plexItem['thumb']) {
+		$plexItem['originalImage'] = $plexItem['imageURL'] = "plugins/images/cache/no-list.png";
+		$plexItem['key'] = "no-list";
+	}
+	if (isset($useImage)) {
+		$plexItem['useImage'] = $useImage;
+	}
+	return $plexItem;
 }
-function plexConnect($action, $key=null)
+
+function plexConnect($action, $key = null)
 {
-    if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
-        $url = qualifyURL($GLOBALS['plexURL']);
-        $ignore = array();
-        switch ($action) {
-            case 'streams':
-                $url = $url."/status/sessions?X-Plex-Token=".$GLOBALS['plexToken'];
-                break;
-            case 'recent':
-                $url = $url."/library/recentlyAdded?X-Plex-Token=".$GLOBALS['plexToken'];
-                break;
-            case 'metadata':
-                $url = $url."/library/metadata/".$key."?X-Plex-Token=".$GLOBALS['plexToken'];
-                break;
-            case 'playlists':
-                $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
-                break;
-            case 'search':
-                $url = $url."/search?query=".rawurlencode($key)."&X-Plex-Token=".$GLOBALS['plexToken'];
-                $ignore = array('artist', 'episode');
-                break;
-            default:
-                # code...
-                break;
-        }
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            libxml_use_internal_errors(true);
-            if ($response->success) {
-                $items = array();
-                $plex = simplexml_load_string($response->body);
-                foreach ($plex as $child) {
-                    if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
-                        $items[] = resolvePlexItem($child);
-                    }
-                }
-                $api['content'] = $items;
-                $api['plexID'] = $GLOBALS['plexID'];
-                $api['showNames'] = true;
-                $api['group'] = '1';
-                return $api;
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-    }
-    return false;
+	if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']))) {
+		$url = qualifyURL($GLOBALS['plexURL']);
+		$ignore = array();
+		switch ($action) {
+			case 'streams':
+				$url = $url . "/status/sessions?X-Plex-Token=" . $GLOBALS['plexToken'];
+				break;
+			case 'recent':
+				$url = $url . "/library/recentlyAdded?X-Plex-Token=" . $GLOBALS['plexToken'];
+				break;
+			case 'metadata':
+				$url = $url . "/library/metadata/" . $key . "?X-Plex-Token=" . $GLOBALS['plexToken'];
+				break;
+			case 'playlists':
+				$url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
+				break;
+			case 'search':
+				$url = $url . "/search?query=" . rawurlencode($key) . "&X-Plex-Token=" . $GLOBALS['plexToken'];
+				$ignore = array('artist', 'episode');
+				break;
+			default:
+				# code...
+				break;
+		}
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			libxml_use_internal_errors(true);
+			if ($response->success) {
+				$items = array();
+				$plex = simplexml_load_string($response->body);
+				foreach ($plex as $child) {
+					if (!in_array($child['type'], $ignore) && isset($child['librarySectionID'])) {
+						$items[] = resolvePlexItem($child);
+					}
+				}
+				$api['content'] = $items;
+				$api['plexID'] = $GLOBALS['plexID'];
+				$api['showNames'] = true;
+				$api['group'] = '1';
+				return $api;
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+	}
+	return false;
 }
+
 function getPlexPlaylists()
 {
-    if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
-        $url = qualifyURL($GLOBALS['plexURL']);
-        $url = $url."/playlists?X-Plex-Token=".$GLOBALS['plexToken'];
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            libxml_use_internal_errors(true);
-            if ($response->success) {
-                $items = array();
-                $plex = simplexml_load_string($response->body);
-                foreach ($plex as $child) {
-                    if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
-                        $playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
-                        $playlistURL = qualifyURL($GLOBALS['plexURL']);
-                        $playlistURL = $playlistURL.$child['key']."?X-Plex-Token=".$GLOBALS['plexToken'];
-                        $options = (localURL($url)) ? array('verify' => false ) : array();
-                        $playlistResponse = Requests::get($playlistURL, array(), $options);
-                        if ($playlistResponse->success) {
-                            $playlistResponse = simplexml_load_string($playlistResponse->body);
-                            $items[$playlistTitleClean]['title'] = (string)$child['title'];
-                            foreach ($playlistResponse->Video as $playlistItem) {
-                                $items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
-                            }
-                        }
-                    }
-                }
-                $api['content'] = $items;
-                $api['plexID'] = $GLOBALS['plexID'];
-                $api['showNames'] = true;
-                $api['group'] = '1';
-                return $api;
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'Plex Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-    }
-    return false;
+	if ($GLOBALS['homepagePlexEnabled'] && !empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken']) && !empty($GLOBALS['plexID'] && qualifyRequest($GLOBALS['homepagePlexAuth']) && qualifyRequest($GLOBALS['homepagePlexPlaylistAuth']) && $GLOBALS['homepagePlexPlaylist'])) {
+		$url = qualifyURL($GLOBALS['plexURL']);
+		$url = $url . "/playlists?X-Plex-Token=" . $GLOBALS['plexToken'];
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			libxml_use_internal_errors(true);
+			if ($response->success) {
+				$items = array();
+				$plex = simplexml_load_string($response->body);
+				foreach ($plex as $child) {
+					if ($child['playlistType'] == "video" && strpos(strtolower($child['title']), 'private') === false) {
+						$playlistTitleClean = preg_replace("/(\W)+/", "", (string)$child['title']);
+						$playlistURL = qualifyURL($GLOBALS['plexURL']);
+						$playlistURL = $playlistURL . $child['key'] . "?X-Plex-Token=" . $GLOBALS['plexToken'];
+						$options = (localURL($url)) ? array('verify' => false) : array();
+						$playlistResponse = Requests::get($playlistURL, array(), $options);
+						if ($playlistResponse->success) {
+							$playlistResponse = simplexml_load_string($playlistResponse->body);
+							$items[$playlistTitleClean]['title'] = (string)$child['title'];
+							foreach ($playlistResponse->Video as $playlistItem) {
+								$items[$playlistTitleClean][] = resolvePlexItem($playlistItem);
+							}
+						}
+					}
+				}
+				$api['content'] = $items;
+				$api['plexID'] = $GLOBALS['plexID'];
+				$api['showNames'] = true;
+				$api['group'] = '1';
+				return $api;
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'Plex Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+	}
+	return false;
 }
-function embyConnect($action, $key=null, $skip=false)
+
+function embyConnect($action, $key = null, $skip = false)
 {
-    if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
-        $url = qualifyURL($GLOBALS['embyURL']);
-        switch ($action) {
-            case 'streams':
-                $url = $url.'/Sessions?api_key='.$GLOBALS['embyToken'];
-                break;
-            case 'recent':
-                $username = false;
-                if (isset($GLOBALS['organizrUser']['username'])) {
-                    $username = strtolower($GLOBALS['organizrUser']['username']);
-                }
-                // Get A User
-                $userIds = $url."/Users?api_key=".$GLOBALS['embyToken'];
-                $showPlayed = true;
-                try {
-                    $options = (localURL($userIds)) ? array('verify' => false ) : array();
-                    $response = Requests::get($userIds, array(), $options);
-                    if ($response->success) {
-                        $emby = json_decode($response->body, true);
-                        foreach ($emby as $value) { // Scan for admin user
-                            if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
-                                $userId = $value['Id'];
-                            }
-                            if ($username && strtolower($value['Name']) == $username) {
-                                $userId = $value['Id'];
-                                $showPlayed = false;
-                                break;
-                            }
-                        }
-                    }
-                } catch (Requests_Exception $e) {
-                    writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-                };
-                $url = $url.'/Users/'.$userId.'/Items/Latest?EnableImages=false&Limit=100&api_key='.$GLOBALS['embyToken'].($showPlayed?'':'&IsPlayed=false');
-                break;
-            case 'metadata':
-                $skip = true;
-                break;
-            default:
-                # code...
-                break;
-        }
-        if ($skip && $key) {
-            $items[] = resolveEmbyItem(array('Id'=>$key));
-            $api['content'] = $items;
-            return $api;
-        }
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->success) {
-                $items = array();
-                $emby = json_decode($response->body, true);
-                foreach ($emby as $child) {
-                    if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
-                        $items[] = resolveEmbyItem($child);
-                    }
-                }
-                $api['content'] = array_filter($items);
-                return $api;
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'Emby Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-    }
-    return false;
+	if ($GLOBALS['homepageEmbyEnabled'] && !empty($GLOBALS['embyURL']) && !empty($GLOBALS['embyToken']) && qualifyRequest($GLOBALS['homepageEmbyAuth'])) {
+		$url = qualifyURL($GLOBALS['embyURL']);
+		switch ($action) {
+			case 'streams':
+				$url = $url . '/Sessions?api_key=' . $GLOBALS['embyToken'];
+				break;
+			case 'recent':
+				$username = false;
+				if (isset($GLOBALS['organizrUser']['username'])) {
+					$username = strtolower($GLOBALS['organizrUser']['username']);
+				}
+				// Get A User
+				$userIds = $url . "/Users?api_key=" . $GLOBALS['embyToken'];
+				$showPlayed = true;
+				try {
+					$options = (localURL($userIds)) ? array('verify' => false) : array();
+					$response = Requests::get($userIds, array(), $options);
+					if ($response->success) {
+						$emby = json_decode($response->body, true);
+						foreach ($emby as $value) { // Scan for admin user
+							if (isset($value['Policy']) && isset($value['Policy']['IsAdministrator']) && $value['Policy']['IsAdministrator']) {
+								$userId = $value['Id'];
+							}
+							if ($username && strtolower($value['Name']) == $username) {
+								$userId = $value['Id'];
+								$showPlayed = false;
+								break;
+							}
+						}
+					}
+				} catch (Requests_Exception $e) {
+					writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				};
+				$url = $url . '/Users/' . $userId . '/Items/Latest?EnableImages=false&Limit=100&api_key=' . $GLOBALS['embyToken'] . ($showPlayed ? '' : '&IsPlayed=false');
+				break;
+			case 'metadata':
+				$skip = true;
+				break;
+			default:
+				# code...
+				break;
+		}
+		if ($skip && $key) {
+			$items[] = resolveEmbyItem(array('Id' => $key));
+			$api['content'] = $items;
+			return $api;
+		}
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->success) {
+				$items = array();
+				$emby = json_decode($response->body, true);
+				foreach ($emby as $child) {
+					if (isset($child['NowPlayingItem']) || isset($child['Name'])) {
+						$items[] = resolveEmbyItem($child);
+					}
+				}
+				$api['content'] = array_filter($items);
+				return $api;
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'Emby Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+	}
+	return false;
 }
+
 function sabnzbdConnect()
 {
-    if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
-        $url = qualifyURL($GLOBALS['sabnzbdURL']);
-        $url = $url.'/api?mode=queue&output=json&apikey='.$GLOBALS['sabnzbdToken'];
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->success) {
-                $api['content']['queueItems'] = json_decode($response->body, true);
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $url = qualifyURL($GLOBALS['sabnzbdURL']);
-        $url = $url.'/api?mode=history&output=json&apikey='.$GLOBALS['sabnzbdToken'];
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->success) {
-                $api['content']['historyItems']= json_decode($response->body, true);
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'SabNZBd Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $api['content'] = isset($api['content']) ? $api['content'] : false;
-        return $api;
-    }
-    return false;
+	if ($GLOBALS['homepageSabnzbdEnabled'] && !empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) && qualifyRequest($GLOBALS['homepageSabnzbdAuth'])) {
+		$url = qualifyURL($GLOBALS['sabnzbdURL']);
+		$url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->success) {
+				$api['content']['queueItems'] = json_decode($response->body, true);
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$url = qualifyURL($GLOBALS['sabnzbdURL']);
+		$url = $url . '/api?mode=history&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->success) {
+				$api['content']['historyItems'] = json_decode($response->body, true);
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'SabNZBd Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$api['content'] = isset($api['content']) ? $api['content'] : false;
+		return $api;
+	}
+	return false;
 }
+
 function nzbgetConnect()
 {
-    if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
-        $url = qualifyURL($GLOBALS['nzbgetURL']);
-        $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/listgroups';
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->success) {
-                $api['content']['queueItems'] = json_decode($response->body, true);
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $url = qualifyURL($GLOBALS['nzbgetURL']);
-        $url = $url.'/'.$GLOBALS['nzbgetUsername'].':'.decrypt($GLOBALS['nzbgetPassword']).'/jsonrpc/history';
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->success) {
-                $api['content']['historyItems']= json_decode($response->body, true);
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'NZBGet Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $api['content'] = isset($api['content']) ? $api['content'] : false;
-        return $api;
-    }
-    return false;
+	if ($GLOBALS['homepageNzbgetEnabled'] && !empty($GLOBALS['nzbgetURL']) && qualifyRequest($GLOBALS['homepageNzbgetAuth'])) {
+		$url = qualifyURL($GLOBALS['nzbgetURL']);
+		$url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->success) {
+				$api['content']['queueItems'] = json_decode($response->body, true);
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$url = qualifyURL($GLOBALS['nzbgetURL']);
+		$url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/history';
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->success) {
+				$api['content']['historyItems'] = json_decode($response->body, true);
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'NZBGet Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$api['content'] = isset($api['content']) ? $api['content'] : false;
+		return $api;
+	}
+	return false;
 }
+
 function transmissionConnect()
 {
-    if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
-        $digest = qualifyURL($GLOBALS['transmissionURL'], true);
-        $passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'].':'.decrypt($GLOBALS['transmissionPassword'])."@" : '';
-        $url = $digest['scheme'].'://'.$passwordInclude.$digest['host'].$digest['port'].$digest['path'].'/rpc';
-        try {
-            $options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false ) : array();
-            $response = Requests::get($url, array(), $options);
-            if ($response->headers['x-transmission-session-id']) {
-                $headers = array(
-                    'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
-                    'Content-Type' => 'application/json'
-                );
-                $data = array(
-                    'method' => 'torrent-get',
-                    'arguments' => array(
-                        'fields' => array(
-                            "id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir","errorString"
-                        ),
-                    ),
-                    'tags' => ''
-                );
-                $response = Requests::post($url, $headers, json_encode($data), $options);
-                if ($response->success) {
-                    $torrentList = json_decode($response->body, true)['arguments']['torrents'];
-                    if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
-                        $filter = array();
-                        $torrents['arguments']['torrents'] = array();
-                        if ($GLOBALS['transmissionHideSeeding']) {
-                            array_push($filter, 6, 5);
-                        }
-                        if ($GLOBALS['transmissionHideCompleted']) {
-                            array_push($filter, 0);
-                        }
-                        foreach ($torrentList as $key => $value) {
-                            if (!in_array($value['status'], $filter)) {
-                                $torrents['arguments']['torrents'][] = $value;
-                            }
-                        }
-                    } else {
-                        $torrents = json_decode($response->body, true);
-                    }
-                    $api['content']['queueItems'] = $torrents;
-                    $api['content']['historyItems'] = false;
-                }
-            } else {
-                writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'Transmission Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $api['content'] = isset($api['content']) ? $api['content'] : false;
-        return $api;
-    }
-    return false;
+	if ($GLOBALS['homepageTransmissionEnabled'] && !empty($GLOBALS['transmissionURL']) && qualifyRequest($GLOBALS['homepageTransmissionAuth'])) {
+		$digest = qualifyURL($GLOBALS['transmissionURL'], true);
+		$passwordInclude = ($GLOBALS['transmissionUsername'] != '' && $GLOBALS['transmissionPassword'] != '') ? $GLOBALS['transmissionUsername'] . ':' . decrypt($GLOBALS['transmissionPassword']) . "@" : '';
+		$url = $digest['scheme'] . '://' . $passwordInclude . $digest['host'] . $digest['port'] . $digest['path'] . '/rpc';
+		try {
+			$options = (localURL($GLOBALS['transmissionURL'])) ? array('verify' => false) : array();
+			$response = Requests::get($url, array(), $options);
+			if ($response->headers['x-transmission-session-id']) {
+				$headers = array(
+					'X-Transmission-Session-Id' => $response->headers['x-transmission-session-id'],
+					'Content-Type' => 'application/json'
+				);
+				$data = array(
+					'method' => 'torrent-get',
+					'arguments' => array(
+						'fields' => array(
+							"id", "name", "totalSize", "eta", "isFinished", "isStalled", "percentDone", "rateDownload", "status", "downloadDir", "errorString"
+						),
+					),
+					'tags' => ''
+				);
+				$response = Requests::post($url, $headers, json_encode($data), $options);
+				if ($response->success) {
+					$torrentList = json_decode($response->body, true)['arguments']['torrents'];
+					if ($GLOBALS['transmissionHideSeeding'] || $GLOBALS['transmissionHideCompleted']) {
+						$filter = array();
+						$torrents['arguments']['torrents'] = array();
+						if ($GLOBALS['transmissionHideSeeding']) {
+							array_push($filter, 6, 5);
+						}
+						if ($GLOBALS['transmissionHideCompleted']) {
+							array_push($filter, 0);
+						}
+						foreach ($torrentList as $key => $value) {
+							if (!in_array($value['status'], $filter)) {
+								$torrents['arguments']['torrents'][] = $value;
+							}
+						}
+					} else {
+						$torrents = json_decode($response->body, true);
+					}
+					$api['content']['queueItems'] = $torrents;
+					$api['content']['historyItems'] = false;
+				}
+			} else {
+				writeLog('error', 'Transmission Connect Function - Error: Could not get session ID', 'SYSTEM');
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'Transmission Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$api['content'] = isset($api['content']) ? $api['content'] : false;
+		return $api;
+	}
+	return false;
 }
+
 function qBittorrentConnect()
 {
-    if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
-        $digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
-        $data = array('username'=>$GLOBALS['qBittorrentUsername'], 'password'=> decrypt($GLOBALS['qBittorrentPassword']));
-        $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/login';
-        try {
-            $options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false ) : array();
-            $response = Requests::post($url, array(), $data, $options);
-            $reflection = new ReflectionClass($response->cookies);
-            $cookie = $reflection->getProperty("cookies");
-            $cookie->setAccessible(true);
-            $cookie = $cookie->getValue($response->cookies);
-            if ($cookie) {
-                $headers = array(
-                    'Cookie' => 'SID=' . $cookie['SID']->value
-                );
-                $reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
-                $url = $digest['scheme'].'://'.$digest['host'].$digest['port'].$digest['path'].'/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
-                $response = Requests::get($url, $headers, $options);
-                if ($response) {
-                    $torrentList = json_decode($response->body, true);
-                    if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
-                        $filter = array();
-                        $torrents['arguments']['torrents'] = array();
-                        if ($GLOBALS['qBittorrentHideSeeding']) {
-                            array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
-                        }
-                        if ($GLOBALS['qBittorrentHideCompleted']) {
-                            array_push($filter, 'pausedUP');
-                        }
-                        foreach ($torrentList as $key => $value) {
-                            if (!in_array($value['state'], $filter)) {
-                                $torrents['arguments']['torrents'][] = $value;
-                            }
-                        }
-                    } else {
-                        $torrents['arguments']['torrents'] = json_decode($response->body, true);
-                    }
-                    $api['content']['queueItems'] = $torrents;
-                    $api['content']['historyItems'] = false;
-                }
-            } else {
-                writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'qBittorrent Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-        $api['content'] = isset($api['content']) ? $api['content'] : false;
-        return $api;
-    }
-    return false;
+	if ($GLOBALS['homepageqBittorrentEnabled'] && !empty($GLOBALS['qBittorrentURL']) && qualifyRequest($GLOBALS['homepageqBittorrentAuth'])) {
+		$digest = qualifyURL($GLOBALS['qBittorrentURL'], true);
+		$data = array('username' => $GLOBALS['qBittorrentUsername'], 'password' => decrypt($GLOBALS['qBittorrentPassword']));
+		$url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/login';
+		try {
+			$options = (localURL($GLOBALS['qBittorrentURL'])) ? array('verify' => false) : array();
+			$response = Requests::post($url, array(), $data, $options);
+			$reflection = new ReflectionClass($response->cookies);
+			$cookie = $reflection->getProperty("cookies");
+			$cookie->setAccessible(true);
+			$cookie = $cookie->getValue($response->cookies);
+			if ($cookie) {
+				$headers = array(
+					'Cookie' => 'SID=' . $cookie['SID']->value
+				);
+				$reverse = $GLOBALS['qBittorrentReverseSorting'] ? 'true' : 'false';
+				$url = $digest['scheme'] . '://' . $digest['host'] . $digest['port'] . $digest['path'] . '/query/torrents?sort=' . $GLOBALS['qBittorrentSortOrder'] . '&reverse=' . $reverse;
+				$response = Requests::get($url, $headers, $options);
+				if ($response) {
+					$torrentList = json_decode($response->body, true);
+					if ($GLOBALS['qBittorrentHideSeeding'] || $GLOBALS['qBittorrentHideCompleted']) {
+						$filter = array();
+						$torrents['arguments']['torrents'] = array();
+						if ($GLOBALS['qBittorrentHideSeeding']) {
+							array_push($filter, 'uploading', 'stalledUP', 'queuedUP');
+						}
+						if ($GLOBALS['qBittorrentHideCompleted']) {
+							array_push($filter, 'pausedUP');
+						}
+						foreach ($torrentList as $key => $value) {
+							if (!in_array($value['state'], $filter)) {
+								$torrents['arguments']['torrents'][] = $value;
+							}
+						}
+					} else {
+						$torrents['arguments']['torrents'] = json_decode($response->body, true);
+					}
+					$api['content']['queueItems'] = $torrents;
+					$api['content']['historyItems'] = false;
+				}
+			} else {
+				writeLog('error', 'qBittorrent Connect Function - Error: Could not get session ID', 'SYSTEM');
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'qBittorrent Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+		$api['content'] = isset($api['content']) ? $api['content'] : false;
+		return $api;
+	}
+	return false;
 }
+
 function delugeConnect()
 {
-    if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
-        try {
-            $deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
-            $torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
-	        if ($GLOBALS['delugeHideSeeding'] || $GLOBALS['delugeHideCompleted']) {
-		        $filter = array();
-		        if ($GLOBALS['delugeHideSeeding']) {
-			        array_push($filter, 'Seeding', 'Uploading', 'queuedUP');
-		        }
-		        if ($GLOBALS['delugeHideCompleted']) {
-			        array_push($filter, 'Seeding', 'Completed');
-		        }
-		        //prettyPrint($torrents);
-		        foreach ($torrents as $key => $value) {
-			        if (!in_array($value->state, $filter)) {
-				        $api['content']['queueItems'][] = $value;
-			        }
-		        }
-	        } else {
-		        $api['content']['queueItems'] = $torrents;
-	        }
-            //$api['content']['queueItems'] = $torrents;
-            $api['content']['historyItems'] = false;
-        } catch (Excecption $e) {
-            writeLog('error', 'Deluge Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        }
-    }
-    $api['content'] = isset($api['content']) ? $api['content'] : false;
-    return $api;
+	if ($GLOBALS['homepageDelugeEnabled'] && !empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword']) && qualifyRequest($GLOBALS['homepageDelugeAuth'])) {
+		try {
+			$deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
+			$torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
+			if ($GLOBALS['delugeHideSeeding'] || $GLOBALS['delugeHideCompleted']) {
+				$filter = array();
+				if ($GLOBALS['delugeHideSeeding']) {
+					array_push($filter, 'Seeding', 'Uploading', 'queuedUP');
+				}
+				if ($GLOBALS['delugeHideCompleted']) {
+					array_push($filter, 'Seeding', 'Completed');
+				}
+				//prettyPrint($torrents);
+				foreach ($torrents as $key => $value) {
+					if (!in_array($value->state, $filter)) {
+						$api['content']['queueItems'][] = $value;
+					}
+				}
+			} else {
+				$api['content']['queueItems'] = $torrents;
+			}
+			//$api['content']['queueItems'] = $torrents;
+			$api['content']['historyItems'] = false;
+		} catch (Excecption $e) {
+			writeLog('error', 'Deluge Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		}
+	}
+	$api['content'] = isset($api['content']) ? $api['content'] : false;
+	return $api;
 }
+
 function getCalendar()
 {
-    $startDate = date('Y-m-d', strtotime("-".$GLOBALS['calendarStart']." days"));
-    $endDate = date('Y-m-d', strtotime("+".$GLOBALS['calendarEnd']." days"));
-    $calendarItems = array();
-    // SONARR CONNECT
-    if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
-        $sonarrs = array();
-        $sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
-        $sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
-        if (count($sonarrURLList) == count($sonarrTokenList)) {
-            foreach ($sonarrURLList as $key => $value) {
-                $sonarrs[$key] = array(
-                    'url' => $value,
-                    'token' => $sonarrTokenList[$key]
-                );
-            }
-            foreach ($sonarrs as $key => $value) {
-                try {
-                    $sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
-                    $sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate), $key);
-                } catch (Exception $e) {
-                    writeLog('error', 'Sonarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-                }
-                if (!empty($sonarrCalendar)) {
-                    $calendarItems = array_merge($calendarItems, $sonarrCalendar);
-                }
-            }
-        }
-    }
-    // RADARR CONNECT
-    if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
-        $radarrs = array();
-        $radarrURLList = explode(',', $GLOBALS['radarrURL']);
-        $radarrTokenList = explode(',', $GLOBALS['radarrToken']);
-        if (count($radarrURLList) == count($radarrTokenList)) {
-            foreach ($radarrURLList as $key => $value) {
-                $radarrs[$key] = array(
-                    'url' => $value,
-                    'token' => $radarrTokenList[$key]
-                );
-            }
-            foreach ($radarrs as $key => $value) {
-                try {
-                    $radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
-                    $radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate), $key, $value['url']);
-                } catch (Exception $e) {
-                    writeLog('error', 'Radarr Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-                }
-                if (!empty($radarrCalendar)) {
-                    $calendarItems = array_merge($calendarItems, $radarrCalendar);
-                }
-            }
-        }
-    }
-    // SICKRAGE/BEARD/MEDUSA CONNECT
-    if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
-        $sicks = array();
-        $sickURLList = explode(',', $GLOBALS['sickrageURL']);
-        $sickTokenList = explode(',', $GLOBALS['sickrageToken']);
-        if (count($sickURLList) == count($sickTokenList)) {
-            foreach ($sickURLList as $key => $value) {
-                $sicks[$key] = array(
-                    'url' => $value,
-                    'token' => $sickTokenList[$key]
-                );
-            }
-            foreach ($sicks as $key => $value) {
-                try {
-                    $sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
-                    $sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
-                    $sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
-                    if (!empty($sickrageFuture)) {
-                        $calendarItems = array_merge($calendarItems, $sickrageFuture);
-                    }
-                    if (!empty($sickrageHistory)) {
-                        $calendarItems = array_merge($calendarItems, $sickrageHistory);
-                    }
-                } catch (Exception $e) {
-                    writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-                }
-            }
-        }
-    }
-    // COUCHPOTATO CONNECT
-    if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
-        $couchs = array();
-        $couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
-        $couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
-        if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
-            foreach ($couchpotatoURLList as $key => $value) {
-                $couchs[$key] = array(
-                    'url' => $value,
-                    'token' => $couchpotatoTokenList[$key]
-                );
-            }
-            foreach ($couchs as $key => $value) {
-                try {
-                    $couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
-                    $couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
-                    if (!empty($couchCalendar)) {
-                        $calendarItems = array_merge($calendarItems, $couchCalendar);
-                    }
-                } catch (Exception $e) {
-                    writeLog('error', 'Sickrage Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-                }
-            }
-        }
-    }
-
-    return ($calendarItems) ? $calendarItems : false;
+	$startDate = date('Y-m-d', strtotime("-" . $GLOBALS['calendarStart'] . " days"));
+	$endDate = date('Y-m-d', strtotime("+" . $GLOBALS['calendarEnd'] . " days"));
+	$calendarItems = array();
+	// SONARR CONNECT
+	if ($GLOBALS['homepageSonarrEnabled'] && qualifyRequest($GLOBALS['homepageSonarrAuth']) && !empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
+		$sonarrs = array();
+		$sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
+		$sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
+		if (count($sonarrURLList) == count($sonarrTokenList)) {
+			foreach ($sonarrURLList as $key => $value) {
+				$sonarrs[$key] = array(
+					'url' => $value,
+					'token' => $sonarrTokenList[$key]
+				);
+			}
+			foreach ($sonarrs as $key => $value) {
+				try {
+					$sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
+					$sonarrCalendar = getSonarrCalendar($sonarr->getCalendar($startDate, $endDate), $key);
+				} catch (Exception $e) {
+					writeLog('error', 'Sonarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				}
+				if (!empty($sonarrCalendar)) {
+					$calendarItems = array_merge($calendarItems, $sonarrCalendar);
+				}
+			}
+		}
+	}
+	// RADARR CONNECT
+	if ($GLOBALS['homepageRadarrEnabled'] && qualifyRequest($GLOBALS['homepageRadarrAuth']) && !empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
+		$radarrs = array();
+		$radarrURLList = explode(',', $GLOBALS['radarrURL']);
+		$radarrTokenList = explode(',', $GLOBALS['radarrToken']);
+		if (count($radarrURLList) == count($radarrTokenList)) {
+			foreach ($radarrURLList as $key => $value) {
+				$radarrs[$key] = array(
+					'url' => $value,
+					'token' => $radarrTokenList[$key]
+				);
+			}
+			foreach ($radarrs as $key => $value) {
+				try {
+					$radarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
+					$radarrCalendar = getRadarrCalendar($radarr->getCalendar($startDate, $endDate), $key, $value['url']);
+				} catch (Exception $e) {
+					writeLog('error', 'Radarr Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				}
+				if (!empty($radarrCalendar)) {
+					$calendarItems = array_merge($calendarItems, $radarrCalendar);
+				}
+			}
+		}
+	}
+	// SICKRAGE/BEARD/MEDUSA CONNECT
+	if ($GLOBALS['homepageSickrageEnabled'] && qualifyRequest($GLOBALS['homepageSickrageAuth']) && !empty($GLOBALS['sickrageURL']) && !empty($GLOBALS['sickrageToken'])) {
+		$sicks = array();
+		$sickURLList = explode(',', $GLOBALS['sickrageURL']);
+		$sickTokenList = explode(',', $GLOBALS['sickrageToken']);
+		if (count($sickURLList) == count($sickTokenList)) {
+			foreach ($sickURLList as $key => $value) {
+				$sicks[$key] = array(
+					'url' => $value,
+					'token' => $sickTokenList[$key]
+				);
+			}
+			foreach ($sicks as $key => $value) {
+				try {
+					$sickrage = new Kryptonit3\SickRage\SickRage($value['url'], $value['token']);
+					$sickrageFuture = getSickrageCalendarWanted($sickrage->future(), $key);
+					$sickrageHistory = getSickrageCalendarHistory($sickrage->history("100", "downloaded"), $key);
+					if (!empty($sickrageFuture)) {
+						$calendarItems = array_merge($calendarItems, $sickrageFuture);
+					}
+					if (!empty($sickrageHistory)) {
+						$calendarItems = array_merge($calendarItems, $sickrageHistory);
+					}
+				} catch (Exception $e) {
+					writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				}
+			}
+		}
+	}
+	// COUCHPOTATO CONNECT
+	if ($GLOBALS['homepageCouchpotatoEnabled'] && qualifyRequest($GLOBALS['homepageCouchpotatoAuth']) && !empty($GLOBALS['couchpotatoURL']) && !empty($GLOBALS['couchpotatoToken'])) {
+		$couchs = array();
+		$couchpotatoURLList = explode(',', $GLOBALS['couchpotatoURL']);
+		$couchpotatoTokenList = explode(',', $GLOBALS['couchpotatoToken']);
+		if (count($couchpotatoURLList) == count($couchpotatoTokenList)) {
+			foreach ($couchpotatoURLList as $key => $value) {
+				$couchs[$key] = array(
+					'url' => $value,
+					'token' => $couchpotatoTokenList[$key]
+				);
+			}
+			foreach ($couchs as $key => $value) {
+				try {
+					$couchpotato = new Kryptonit3\CouchPotato\CouchPotato($value['url'], $value['token']);
+					$couchCalendar = getCouchCalendar($couchpotato->getMediaList(), $key);
+					if (!empty($couchCalendar)) {
+						$calendarItems = array_merge($calendarItems, $couchCalendar);
+					}
+				} catch (Exception $e) {
+					writeLog('error', 'Sickrage Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+				}
+			}
+		}
+	}
+	
+	return ($calendarItems) ? $calendarItems : false;
 }
+
 function getSonarrCalendar($array, $number)
 {
-    $array = json_decode($array, true);
-    $gotCalendar = array();
-    $i = 0;
-    foreach ($array as $child) {
-        $i++;
-        $seriesName = $child['series']['title'];
-        $seriesID = $child['series']['tvdbId'];
-        $episodeID = $child['series']['tvdbId'];
-        if (!isset($episodeID)) {
-            $episodeID = "";
-        }
-        //$episodeName = htmlentities($child['title'], ENT_QUOTES);
-        if ($child['episodeNumber'] == "1") {
-            $episodePremier = "true";
-        } else {
-            $episodePremier = "false";
-        }
-        $episodeAirDate = $child['airDateUtc'];
-        $episodeAirDate = strtotime($episodeAirDate);
-        $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
-        if (new DateTime() < new DateTime($episodeAirDate)) {
-            $unaired = true;
-        }
-        $downloaded = $child['hasFile'];
-        if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
-            $downloaded = "text-primary animated flash";
-        } elseif ($downloaded == "0" && isset($unaired)) {
-            $downloaded = "text-info";
-        } elseif ($downloaded == "1") {
-            $downloaded = "text-success";
-        } else {
-            $downloaded = "text-danger";
-        }
-
-        $fanart = "/plugins/images/cache/no-np.png";
-        foreach ($child['series']['images'] as $image) {
-            if ($image['coverType'] == "fanart") {
-                $fanart = $image['url'];
-            }
-        }
-        if ($fanart !== "/plugins/images/cache/no-np.png") {
-            $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-            $imageURL = $fanart;
-            $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            if (!file_exists($cacheFile)) {
-                cacheImage($imageURL, $seriesID);
-                unset($imageURL);
-                unset($cacheFile);
-            }
-        }
-        $bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
-        $details = array(
-                "seasonCount" => $child['series']['seasonCount'],
-                "status" => $child['series']['status'],
-                "topTitle" => $seriesName,
-                "bottomTitle" => $bottomTitle,
-                "overview" => isset($child['overview']) ? $child['overview'] : '',
-                "runtime" => $child['series']['runtime'],
-                "image" => $fanart,
-                "ratings" => $child['series']['ratings']['value'],
-                "videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
-                "audioChannels" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
-                "audioCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
-                "videoCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
-                "size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
-                "genres" => $child['series']['genres'],
-            );
-        array_push($gotCalendar, array(
-            "id" => "Sonarr-".$number."-".$i,
-            "title" => $seriesName,
-            "start" => $child['airDateUtc'],
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details
-        ));
-    }
-    if ($i != 0) {
-        return $gotCalendar;
-    }
-    return false;
+	$array = json_decode($array, true);
+	$gotCalendar = array();
+	$i = 0;
+	foreach ($array as $child) {
+		$i++;
+		$seriesName = $child['series']['title'];
+		$seriesID = $child['series']['tvdbId'];
+		$episodeID = $child['series']['tvdbId'];
+		if (!isset($episodeID)) {
+			$episodeID = "";
+		}
+		//$episodeName = htmlentities($child['title'], ENT_QUOTES);
+		if ($child['episodeNumber'] == "1") {
+			$episodePremier = "true";
+		} else {
+			$episodePremier = "false";
+		}
+		$episodeAirDate = $child['airDateUtc'];
+		$episodeAirDate = strtotime($episodeAirDate);
+		$episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
+		if (new DateTime() < new DateTime($episodeAirDate)) {
+			$unaired = true;
+		}
+		$downloaded = $child['hasFile'];
+		if ($downloaded == "0" && isset($unaired) && $episodePremier == "true") {
+			$downloaded = "text-primary animated flash";
+		} elseif ($downloaded == "0" && isset($unaired)) {
+			$downloaded = "text-info";
+		} elseif ($downloaded == "1") {
+			$downloaded = "text-success";
+		} else {
+			$downloaded = "text-danger";
+		}
+		
+		$fanart = "/plugins/images/cache/no-np.png";
+		foreach ($child['series']['images'] as $image) {
+			if ($image['coverType'] == "fanart") {
+				$fanart = $image['url'];
+			}
+		}
+		if ($fanart !== "/plugins/images/cache/no-np.png") {
+			$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+			$imageURL = $fanart;
+			$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			if (!file_exists($cacheFile)) {
+				cacheImage($imageURL, $seriesID);
+				unset($imageURL);
+				unset($cacheFile);
+			}
+		}
+		$bottomTitle = 'S' . sprintf("%02d", $child['seasonNumber']) . 'E' . sprintf("%02d", $child['episodeNumber']) . ' - ' . $child['title'];
+		$details = array(
+			"seasonCount" => $child['series']['seasonCount'],
+			"status" => $child['series']['status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => isset($child['overview']) ? $child['overview'] : '',
+			"runtime" => $child['series']['runtime'],
+			"image" => $fanart,
+			"ratings" => $child['series']['ratings']['value'],
+			"videoQuality" => $child["hasFile"] ? $child['episodeFile']['quality']['quality']['name'] : "unknown",
+			"audioChannels" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioChannels'] : "unknown",
+			"audioCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['audioCodec'] : "unknown",
+			"videoCodec" => $child["hasFile"] ? $child['episodeFile']['mediaInfo']['videoCodec'] : "unknown",
+			"size" => $child["hasFile"] ? $child['episodeFile']['size'] : "unknown",
+			"genres" => $child['series']['genres'],
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sonarr-" . $number . "-" . $i,
+			"title" => $seriesName,
+			"start" => $child['airDateUtc'],
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details
+		));
+	}
+	if ($i != 0) {
+		return $gotCalendar;
+	}
+	return false;
 }
+
 function getRadarrCalendar($array, $number, $url)
 {
-    $array = json_decode($array, true);
-    $gotCalendar = array();
-    $i = 0;
-    foreach ($array as $child) {
-        if (isset($child['physicalRelease'])) {
-            $i++;
-            $movieName = $child['title'];
-            $movieID = $child['tmdbId'];
-            if (!isset($movieID)) {
-                $movieID = "";
-            }
-            $physicalRelease = $child['physicalRelease'];
-            $physicalRelease = strtotime($physicalRelease);
-            $physicalRelease = date("Y-m-d", $physicalRelease);
-            if (new DateTime() < new DateTime($physicalRelease)) {
-                $notReleased = "true";
-            } else {
-                $notReleased = "false";
-            }
-            $downloaded = $child['hasFile'];
-            if ($downloaded == "0" && $notReleased == "true") {
-                $downloaded = "text-info";
-            } elseif ($downloaded == "1") {
-                $downloaded = "text-success";
-            } else {
-                $downloaded = "text-danger";
-            }
-            $banner = "/plugins/images/cache/no-np.png";
-            foreach ($child['images'] as $image) {
-                if ($image['coverType'] == "banner") {
-                    $url = rtrim($url, '/'); //remove trailing slash
-                    $imageUrl = $image['url'];
-                    $urlParts = explode("/", $url);
-                    $imageParts = explode("/", $image['url']);
-
-                    if ($imageParts[1] == end($urlParts)) {
-                        unset($imageParts[1]);
-                        $imageUrl = implode("/", $imageParts);
-                    }
-
-                    $banner = $url . $imageUrl;
-                }
-            }
-            if ($banner !== "/plugins/images/cache/no-np.png") {
-                $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-                $imageURL = $banner;
-                $cacheFile = $cacheDirectory.$movieID.'.jpg';
-                $banner = 'plugins/images/cache/'.$movieID.'.jpg';
-                if (!file_exists($cacheFile)) {
-                    cacheImage($imageURL, $movieID);
-                    unset($imageURL);
-                    unset($cacheFile);
-                }
-            }
-            $alternativeTitles = "";
-            foreach ($child['alternativeTitles'] as $alternative) {
-                $alternativeTitles .= $alternative['title'] . ', ';
-            }
-            $alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
-            $details = array(
-                    "topTitle" => $movieName,
-                    "bottomTitle" => $alternativeTitles,
-                    "status" => $child['status'],
-                    "overview" => $child['overview'],
-                    "runtime" => $child['runtime'],
-                    "image" => $banner,
-                    "ratings" => $child['ratings']['value'],
-                    "videoQuality" => $child["hasFile"] ? $child['movieFile']['quality']['quality']['name'] : "unknown",
-                    "audioChannels" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
-                    "audioCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
-                    "videoCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
-                    "size" => $child["hasFile"] ? $child['movieFile']['size'] : "unknown",
-                    "genres" => $child['genres'],
-                );
-            array_push($gotCalendar, array(
-                "id" => "Radarr-".$number."-".$i,
-                "title" => $movieName,
-                "start" => $physicalRelease,
-                "className" => "bg-calendar movieID--".$movieID,
-                "imagetype" => "film ".$downloaded,
-                "details" => $details
-            ));
-        }
-    }
-    if ($i != 0) {
-        return $gotCalendar;
-    }
+	$array = json_decode($array, true);
+	$gotCalendar = array();
+	$i = 0;
+	foreach ($array as $child) {
+		if (isset($child['physicalRelease'])) {
+			$i++;
+			$movieName = $child['title'];
+			$movieID = $child['tmdbId'];
+			if (!isset($movieID)) {
+				$movieID = "";
+			}
+			$physicalRelease = $child['physicalRelease'];
+			$physicalRelease = strtotime($physicalRelease);
+			$physicalRelease = date("Y-m-d", $physicalRelease);
+			if (new DateTime() < new DateTime($physicalRelease)) {
+				$notReleased = "true";
+			} else {
+				$notReleased = "false";
+			}
+			$downloaded = $child['hasFile'];
+			if ($downloaded == "0" && $notReleased == "true") {
+				$downloaded = "text-info";
+			} elseif ($downloaded == "1") {
+				$downloaded = "text-success";
+			} else {
+				$downloaded = "text-danger";
+			}
+			$banner = "/plugins/images/cache/no-np.png";
+			foreach ($child['images'] as $image) {
+				if ($image['coverType'] == "banner") {
+					$url = rtrim($url, '/'); //remove trailing slash
+					$imageUrl = $image['url'];
+					$urlParts = explode("/", $url);
+					$imageParts = explode("/", $image['url']);
+					
+					if ($imageParts[1] == end($urlParts)) {
+						unset($imageParts[1]);
+						$imageUrl = implode("/", $imageParts);
+					}
+					
+					$banner = $url . $imageUrl;
+				}
+			}
+			if ($banner !== "/plugins/images/cache/no-np.png") {
+				$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+				$imageURL = $banner;
+				$cacheFile = $cacheDirectory . $movieID . '.jpg';
+				$banner = 'plugins/images/cache/' . $movieID . '.jpg';
+				if (!file_exists($cacheFile)) {
+					cacheImage($imageURL, $movieID);
+					unset($imageURL);
+					unset($cacheFile);
+				}
+			}
+			$alternativeTitles = "";
+			foreach ($child['alternativeTitles'] as $alternative) {
+				$alternativeTitles .= $alternative['title'] . ', ';
+			}
+			$alternativeTitles = empty($child['alternativeTitles']) ? "" : substr($alternativeTitles, 0, -2);
+			$details = array(
+				"topTitle" => $movieName,
+				"bottomTitle" => $alternativeTitles,
+				"status" => $child['status'],
+				"overview" => $child['overview'],
+				"runtime" => $child['runtime'],
+				"image" => $banner,
+				"ratings" => $child['ratings']['value'],
+				"videoQuality" => $child["hasFile"] ? $child['movieFile']['quality']['quality']['name'] : "unknown",
+				"audioChannels" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioChannels'] : "unknown",
+				"audioCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['audioFormat'] : "unknown",
+				"videoCodec" => $child["hasFile"] ? $child['movieFile']['mediaInfo']['videoCodec'] : "unknown",
+				"size" => $child["hasFile"] ? $child['movieFile']['size'] : "unknown",
+				"genres" => $child['genres'],
+			);
+			array_push($gotCalendar, array(
+				"id" => "Radarr-" . $number . "-" . $i,
+				"title" => $movieName,
+				"start" => $physicalRelease,
+				"className" => "bg-calendar movieID--" . $movieID,
+				"imagetype" => "film " . $downloaded,
+				"details" => $details
+			));
+		}
+	}
+	if ($i != 0) {
+		return $gotCalendar;
+	}
 	return false;
 }
+
 function getCouchCalendar($array, $number)
 {
-    $api = json_decode($array, true);
-    $gotCalendar = array();
-    $i = 0;
-    foreach ($api['movies'] as $child) {
-        if ($child['status'] == "active" || $child['status'] == "done") {
-            $i++;
-            $movieName = $child['info']['original_title'];
-            $movieID = $child['info']['tmdb_id'];
-            if (!isset($movieID)) {
-                $movieID = "";
-            }
-            $physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
-            $backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
-            $physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
-            $physicalRelease = strtotime($physicalRelease);
-            $physicalRelease = date("Y-m-d", $physicalRelease);
-            if (new DateTime() < new DateTime($physicalRelease)) {
-                $notReleased = "true";
-            } else {
-                $notReleased = "false";
-            }
-            $downloaded = ($child['status'] == "active") ? "0" : "1";
-            if ($downloaded == "0" && $notReleased == "true") {
-                $downloaded = "text-info";
-            } elseif ($downloaded == "1") {
-                $downloaded = "text-success";
-            } else {
-                $downloaded = "text-danger";
-            }
-
-            if (!empty($child['info']['images']['backdrop_original'])) {
-                $banner = $child['info']['images']['backdrop_original'][0];
-            } elseif (!empty($child['info']['images']['backdrop'])) {
-                $banner = $child['info']['images']['backdrop_original'][0];
-            } else {
-                $banner = "/plugins/images/cache/no-np.png";
-            }
-            if ($banner !== "/plugins/images/cache/no-np.png") {
-                $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-                $imageURL = $banner;
-                $cacheFile = $cacheDirectory.$movieID.'.jpg';
-                $banner = 'plugins/images/cache/'.$movieID.'.jpg';
-                if (!file_exists($cacheFile)) {
-                    cacheImage($imageURL, $movieID);
-                    unset($imageURL);
-                    unset($cacheFile);
-                }
-            }
-            $hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
-            $details = array(
-                    "topTitle" => $movieName,
-                    "bottomTitle" => $child['info']['tagline'],
-                    "status" => $child['status'],
-                    "overview" => $child['info']['plot'],
-                    "runtime" => $child['info']['runtime'],
-                    "image" => $banner,
-                    "ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
-                    "videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
-                    "audioChannels" => "",
-                    "audioCodec" => "",
-                    "videoCodec" => "",
-                    "genres" => $child['info']['genres'],
-                );
-
-            array_push($gotCalendar, array(
-                "id" => "CouchPotato-".$number."-".$i,
-                "title" => $movieName,
-                "start" => $physicalRelease,
-                "className" => "bg-calendar calendar-item movieID--".$movieID,
-                "imagetype" => "film ".$downloaded,
-                "details" => $details
-            ));
-        }
-    }
-    if ($i != 0) {
-        return $gotCalendar;
-    }
+	$api = json_decode($array, true);
+	$gotCalendar = array();
+	$i = 0;
+	foreach ($api['movies'] as $child) {
+		if ($child['status'] == "active" || $child['status'] == "done") {
+			$i++;
+			$movieName = $child['info']['original_title'];
+			$movieID = $child['info']['tmdb_id'];
+			if (!isset($movieID)) {
+				$movieID = "";
+			}
+			$physicalRelease = (isset($child['info']['released']) ? $child['info']['released'] : null);
+			$backupRelease = (isset($child['info']['release_date']['theater']) ? $child['info']['release_date']['theater'] : null);
+			$physicalRelease = (isset($physicalRelease) ? $physicalRelease : $backupRelease);
+			$physicalRelease = strtotime($physicalRelease);
+			$physicalRelease = date("Y-m-d", $physicalRelease);
+			if (new DateTime() < new DateTime($physicalRelease)) {
+				$notReleased = "true";
+			} else {
+				$notReleased = "false";
+			}
+			$downloaded = ($child['status'] == "active") ? "0" : "1";
+			if ($downloaded == "0" && $notReleased == "true") {
+				$downloaded = "text-info";
+			} elseif ($downloaded == "1") {
+				$downloaded = "text-success";
+			} else {
+				$downloaded = "text-danger";
+			}
+			
+			if (!empty($child['info']['images']['backdrop_original'])) {
+				$banner = $child['info']['images']['backdrop_original'][0];
+			} elseif (!empty($child['info']['images']['backdrop'])) {
+				$banner = $child['info']['images']['backdrop_original'][0];
+			} else {
+				$banner = "/plugins/images/cache/no-np.png";
+			}
+			if ($banner !== "/plugins/images/cache/no-np.png") {
+				$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+				$imageURL = $banner;
+				$cacheFile = $cacheDirectory . $movieID . '.jpg';
+				$banner = 'plugins/images/cache/' . $movieID . '.jpg';
+				if (!file_exists($cacheFile)) {
+					cacheImage($imageURL, $movieID);
+					unset($imageURL);
+					unset($cacheFile);
+				}
+			}
+			$hasFile = (!empty($child['releases']) && !empty($child['releases'][0]['files']['movie']));
+			$details = array(
+				"topTitle" => $movieName,
+				"bottomTitle" => $child['info']['tagline'],
+				"status" => $child['status'],
+				"overview" => $child['info']['plot'],
+				"runtime" => $child['info']['runtime'],
+				"image" => $banner,
+				"ratings" => isset($child['info']['rating']['imdb'][0]) ? $child['info']['rating']['imdb'][0] : '',
+				"videoQuality" => $hasFile ? $child['releases'][0]['quality'] : "unknown",
+				"audioChannels" => "",
+				"audioCodec" => "",
+				"videoCodec" => "",
+				"genres" => $child['info']['genres'],
+			);
+			
+			array_push($gotCalendar, array(
+				"id" => "CouchPotato-" . $number . "-" . $i,
+				"title" => $movieName,
+				"start" => $physicalRelease,
+				"className" => "bg-calendar calendar-item movieID--" . $movieID,
+				"imagetype" => "film " . $downloaded,
+				"details" => $details
+			));
+		}
+	}
+	if ($i != 0) {
+		return $gotCalendar;
+	}
 	return false;
 }
+
 function getSickrageCalendarWanted($array, $number)
 {
-    $array = json_decode($array, true);
-    $gotCalendar = array();
-    $i = 0;
-    foreach ($array['data']['missed'] as $child) {
-        $i++;
-        $seriesName = $child['show_name'];
-        $seriesID = $child['tvdbid'];
-        $episodeID = $child['tvdbid'];
-        $episodeAirDate = $child['airdate'];
-        $episodeAirDateTime = explode(" ", $child['airs']);
-        $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
-        $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
-        $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
-        if (new DateTime() < new DateTime($episodeAirDate)) {
-            $unaired = true;
-        }
-        $downloaded = "0";
-        if ($downloaded == "0" && isset($unaired)) {
-            $downloaded = "text-info";
-        } elseif ($downloaded == "1") {
-            $downloaded = "text-success";
-        } else {
-            $downloaded = "text-danger";
-        }
-        $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
-
-        $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-        $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-        $fanart = "/plugins/images/cache/no-np.png";
-        if (file_exists($cacheFile)) {
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            unset($cacheFile);
-        }
-
-        $details = array(
-            "seasonCount" => "",
-            "status" => $child['show_status'],
-            "topTitle" => $seriesName,
-            "bottomTitle" => $bottomTitle,
-            "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
-            "runtime" => "",
-            "image" => $fanart,
-            "ratings" => "",
-            "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
-            "audioChannels" => "",
-            "audioCodec" => "",
-            "videoCodec" => "",
-            "size" => "",
-            "genres" => "",
-        );
-        array_push($gotCalendar, array(
-            "id" => "Sick-".$number."-Miss-".$i,
-            "title" => $seriesName,
-            "start" => $episodeAirDate,
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details,
-        ));
-    }
-    foreach ($array['data']['today'] as $child) {
-        $i++;
-        $seriesName = $child['show_name'];
-        $seriesID = $child['tvdbid'];
-        $episodeID = $child['tvdbid'];
-        $episodeAirDate = $child['airdate'];
-        $episodeAirDateTime = explode(" ", $child['airs']);
-        $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
-        $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
-        $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
-        if (new DateTime() < new DateTime($episodeAirDate)) {
-            $unaired = true;
-        }
-        $downloaded = "0";
-        if ($downloaded == "0" && isset($unaired)) {
-            $downloaded = "text-info";
-        } elseif ($downloaded == "1") {
-            $downloaded = "text-success";
-        } else {
-            $downloaded = "text-danger";
-        }
-        $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
-
-        $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-        $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-        $fanart = "/plugins/images/cache/no-np.png";
-        if (file_exists($cacheFile)) {
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            unset($cacheFile);
-        }
-
-        $details = array(
-            "seasonCount" => "",
-            "status" => $child['show_status'],
-            "topTitle" => $seriesName,
-            "bottomTitle" => $bottomTitle,
-            "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
-            "runtime" => "",
-            "image" => $fanart,
-            "ratings" => "",
-            "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
-            "audioChannels" => "",
-            "audioCodec" => "",
-            "videoCodec" => "",
-            "size" => "",
-            "genres" => "",
-        );
-        array_push($gotCalendar, array(
-            "id" => "Sick-".$number."-Today-".$i,
-            "title" => $seriesName,
-            "start" => $episodeAirDate,
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details,
-        ));
-    }
-    foreach ($array['data']['soon'] as $child) {
-        $i++;
-        $seriesName = $child['show_name'];
-        $seriesID = $child['tvdbid'];
-        $episodeID = $child['tvdbid'];
-        $episodeAirDate = $child['airdate'];
-        $episodeAirDateTime = explode(" ", $child['airs']);
-        $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
-        $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
-        $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
-        if (new DateTime() < new DateTime($episodeAirDate)) {
-            $unaired = true;
-        }
-        $downloaded = "0";
-        if ($downloaded == "0" && isset($unaired)) {
-            $downloaded = "text-info";
-        } elseif ($downloaded == "1") {
-            $downloaded = "text-success";
-        } else {
-            $downloaded = "text-danger";
-        }
-        $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
-
-        $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-        $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-        $fanart = "/plugins/images/cache/no-np.png";
-        if (file_exists($cacheFile)) {
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            unset($cacheFile);
-        }
-
-        $details = array(
-            "seasonCount" => "",
-            "status" => $child['show_status'],
-            "topTitle" => $seriesName,
-            "bottomTitle" => $bottomTitle,
-            "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
-            "runtime" => "",
-            "image" => $fanart,
-            "ratings" => "",
-            "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
-            "audioChannels" => "",
-            "audioCodec" => "",
-            "videoCodec" => "",
-            "size" => "",
-            "genres" => "",
-        );
-        array_push($gotCalendar, array(
-            "id" => "Sick-".$number."-Soon-".$i,
-            "title" => $seriesName,
-            "start" => $episodeAirDate,
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details,
-        ));
-    }
-    foreach ($array['data']['later'] as $child) {
-        $i++;
-        $seriesName = $child['show_name'];
-        $seriesID = $child['tvdbid'];
-        $episodeID = $child['tvdbid'];
-        $episodeAirDate = $child['airdate'];
-        $episodeAirDateTime = explode(" ", $child['airs']);
-        $episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1].$episodeAirDateTime[2]));
-        $episodeAirDate = strtotime($episodeAirDate.$episodeAirDateTime);
-        $episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
-        if (new DateTime() < new DateTime($episodeAirDate)) {
-            $unaired = true;
-        }
-        $downloaded = "0";
-        if ($downloaded == "0" && isset($unaired)) {
-            $downloaded = "text-info";
-        } elseif ($downloaded == "1") {
-            $downloaded = "text-success";
-        } else {
-            $downloaded = "text-danger";
-        }
-        $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
-
-        $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-        $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-        $fanart = "/plugins/images/cache/no-np.png";
-        if (file_exists($cacheFile)) {
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            unset($cacheFile);
-        }
-
-        $details = array(
-            "seasonCount" => "",
-            "status" => $child['show_status'],
-            "topTitle" => $seriesName,
-            "bottomTitle" => $bottomTitle,
-            "overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
-            "runtime" => "",
-            "image" => $fanart,
-            "ratings" => "",
-            "videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
-            "audioChannels" => "",
-            "audioCodec" => "",
-            "videoCodec" => "",
-            "size" => "",
-            "genres" => "",
-        );
-        array_push($gotCalendar, array(
-            "id" => "Sick-".$number."-Later-".$i,
-            "title" => $seriesName,
-            "start" => $episodeAirDate,
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details,
-        ));
-    }
-    if ($i != 0) {
-        return $gotCalendar;
-    }
+	$array = json_decode($array, true);
+	$gotCalendar = array();
+	$i = 0;
+	foreach ($array['data']['missed'] as $child) {
+		$i++;
+		$seriesName = $child['show_name'];
+		$seriesID = $child['tvdbid'];
+		$episodeID = $child['tvdbid'];
+		$episodeAirDate = $child['airdate'];
+		$episodeAirDateTime = explode(" ", $child['airs']);
+		$episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
+		$episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
+		$episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
+		if (new DateTime() < new DateTime($episodeAirDate)) {
+			$unaired = true;
+		}
+		$downloaded = "0";
+		if ($downloaded == "0" && isset($unaired)) {
+			$downloaded = "text-info";
+		} elseif ($downloaded == "1") {
+			$downloaded = "text-success";
+		} else {
+			$downloaded = "text-danger";
+		}
+		$bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
+		
+		$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+		$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+		$fanart = "/plugins/images/cache/no-np.png";
+		if (file_exists($cacheFile)) {
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			unset($cacheFile);
+		}
+		
+		$details = array(
+			"seasonCount" => "",
+			"status" => $child['show_status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
+			"runtime" => "",
+			"image" => $fanart,
+			"ratings" => "",
+			"videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
+			"audioChannels" => "",
+			"audioCodec" => "",
+			"videoCodec" => "",
+			"size" => "",
+			"genres" => "",
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sick-" . $number . "-Miss-" . $i,
+			"title" => $seriesName,
+			"start" => $episodeAirDate,
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details,
+		));
+	}
+	foreach ($array['data']['today'] as $child) {
+		$i++;
+		$seriesName = $child['show_name'];
+		$seriesID = $child['tvdbid'];
+		$episodeID = $child['tvdbid'];
+		$episodeAirDate = $child['airdate'];
+		$episodeAirDateTime = explode(" ", $child['airs']);
+		$episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
+		$episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
+		$episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
+		if (new DateTime() < new DateTime($episodeAirDate)) {
+			$unaired = true;
+		}
+		$downloaded = "0";
+		if ($downloaded == "0" && isset($unaired)) {
+			$downloaded = "text-info";
+		} elseif ($downloaded == "1") {
+			$downloaded = "text-success";
+		} else {
+			$downloaded = "text-danger";
+		}
+		$bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
+		
+		$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+		$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+		$fanart = "/plugins/images/cache/no-np.png";
+		if (file_exists($cacheFile)) {
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			unset($cacheFile);
+		}
+		
+		$details = array(
+			"seasonCount" => "",
+			"status" => $child['show_status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
+			"runtime" => "",
+			"image" => $fanart,
+			"ratings" => "",
+			"videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
+			"audioChannels" => "",
+			"audioCodec" => "",
+			"videoCodec" => "",
+			"size" => "",
+			"genres" => "",
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sick-" . $number . "-Today-" . $i,
+			"title" => $seriesName,
+			"start" => $episodeAirDate,
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details,
+		));
+	}
+	foreach ($array['data']['soon'] as $child) {
+		$i++;
+		$seriesName = $child['show_name'];
+		$seriesID = $child['tvdbid'];
+		$episodeID = $child['tvdbid'];
+		$episodeAirDate = $child['airdate'];
+		$episodeAirDateTime = explode(" ", $child['airs']);
+		$episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
+		$episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
+		$episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
+		if (new DateTime() < new DateTime($episodeAirDate)) {
+			$unaired = true;
+		}
+		$downloaded = "0";
+		if ($downloaded == "0" && isset($unaired)) {
+			$downloaded = "text-info";
+		} elseif ($downloaded == "1") {
+			$downloaded = "text-success";
+		} else {
+			$downloaded = "text-danger";
+		}
+		$bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
+		
+		$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+		$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+		$fanart = "/plugins/images/cache/no-np.png";
+		if (file_exists($cacheFile)) {
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			unset($cacheFile);
+		}
+		
+		$details = array(
+			"seasonCount" => "",
+			"status" => $child['show_status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
+			"runtime" => "",
+			"image" => $fanart,
+			"ratings" => "",
+			"videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
+			"audioChannels" => "",
+			"audioCodec" => "",
+			"videoCodec" => "",
+			"size" => "",
+			"genres" => "",
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sick-" . $number . "-Soon-" . $i,
+			"title" => $seriesName,
+			"start" => $episodeAirDate,
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details,
+		));
+	}
+	foreach ($array['data']['later'] as $child) {
+		$i++;
+		$seriesName = $child['show_name'];
+		$seriesID = $child['tvdbid'];
+		$episodeID = $child['tvdbid'];
+		$episodeAirDate = $child['airdate'];
+		$episodeAirDateTime = explode(" ", $child['airs']);
+		$episodeAirDateTime = date("H:i:s", strtotime($episodeAirDateTime[1] . $episodeAirDateTime[2]));
+		$episodeAirDate = strtotime($episodeAirDate . $episodeAirDateTime);
+		$episodeAirDate = date("Y-m-d H:i:s", $episodeAirDate);
+		if (new DateTime() < new DateTime($episodeAirDate)) {
+			$unaired = true;
+		}
+		$downloaded = "0";
+		if ($downloaded == "0" && isset($unaired)) {
+			$downloaded = "text-info";
+		} elseif ($downloaded == "1") {
+			$downloaded = "text-success";
+		} else {
+			$downloaded = "text-danger";
+		}
+		$bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']) . ' - ' . $child['ep_name'];
+		
+		$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+		$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+		$fanart = "/plugins/images/cache/no-np.png";
+		if (file_exists($cacheFile)) {
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			unset($cacheFile);
+		}
+		
+		$details = array(
+			"seasonCount" => "",
+			"status" => $child['show_status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => isset($child['ep_plot']) ? $child['ep_plot'] : '',
+			"runtime" => "",
+			"image" => $fanart,
+			"ratings" => "",
+			"videoQuality" => isset($child["quality"]) ? $child["quality"] : "",
+			"audioChannels" => "",
+			"audioCodec" => "",
+			"videoCodec" => "",
+			"size" => "",
+			"genres" => "",
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sick-" . $number . "-Later-" . $i,
+			"title" => $seriesName,
+			"start" => $episodeAirDate,
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details,
+		));
+	}
+	if ($i != 0) {
+		return $gotCalendar;
+	}
 	return false;
 }
+
 function getSickrageCalendarHistory($array, $number)
 {
-    $array = json_decode($array, true);
-    $gotCalendar = array();
-    $i = 0;
-    foreach ($array['data'] as $child) {
-        $i++;
-        $seriesName = $child['show_name'];
-        $seriesID = $child['tvdbid'];
-        $episodeID = $child['tvdbid'];
-        $episodeAirDate = $child['date'];
-        $downloaded = "text-success";
-        $bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
-
-        $cacheDirectory = dirname(__DIR__, 2).DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR;
-        $cacheFile = $cacheDirectory.$seriesID.'.jpg';
-        $fanart = "/plugins/images/cache/no-np.png";
-        if (file_exists($cacheFile)) {
-            $fanart = 'plugins/images/cache/'.$seriesID.'.jpg';
-            unset($cacheFile);
-        }
-
-        $details = array(
-            "seasonCount" => "",
-            "status" => $child['status'],
-            "topTitle" => $seriesName,
-            "bottomTitle" => $bottomTitle,
-            "overview" => '',
-            "runtime" => $child['series']['runtime'],
-            "image" => $fanart,
-            "ratings" => $child['series']['ratings']['value'],
-            "videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
-            "audioChannels" => "",
-            "audioCodec" => "",
-            "videoCodec" => "",
-            "size" => "",
-            "genres" => "",
-        );
-        array_push($gotCalendar, array(
-            "id" => "Sick-".$number."-History-".$i,
-            "title" => $seriesName,
-            "start" => $episodeAirDate,
-            "className" => "bg-calendar calendar-item tvID--".$episodeID,
-            "imagetype" => "tv ".$downloaded,
-            "details" => $details,
-        ));
-    }
-    if ($i != 0) {
-        return $gotCalendar;
-    }
+	$array = json_decode($array, true);
+	$gotCalendar = array();
+	$i = 0;
+	foreach ($array['data'] as $child) {
+		$i++;
+		$seriesName = $child['show_name'];
+		$seriesID = $child['tvdbid'];
+		$episodeID = $child['tvdbid'];
+		$episodeAirDate = $child['date'];
+		$downloaded = "text-success";
+		$bottomTitle = 'S' . sprintf("%02d", $child['season']) . 'E' . sprintf("%02d", $child['episode']);
+		
+		$cacheDirectory = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
+		$cacheFile = $cacheDirectory . $seriesID . '.jpg';
+		$fanart = "/plugins/images/cache/no-np.png";
+		if (file_exists($cacheFile)) {
+			$fanart = 'plugins/images/cache/' . $seriesID . '.jpg';
+			unset($cacheFile);
+		}
+		
+		$details = array(
+			"seasonCount" => "",
+			"status" => $child['status'],
+			"topTitle" => $seriesName,
+			"bottomTitle" => $bottomTitle,
+			"overview" => '',
+			"runtime" => $child['series']['runtime'],
+			"image" => $fanart,
+			"ratings" => $child['series']['ratings']['value'],
+			"videoQuality" => isset($child["quality"]) ? $child['quality'] : "unknown",
+			"audioChannels" => "",
+			"audioCodec" => "",
+			"videoCodec" => "",
+			"size" => "",
+			"genres" => "",
+		);
+		array_push($gotCalendar, array(
+			"id" => "Sick-" . $number . "-History-" . $i,
+			"title" => $seriesName,
+			"start" => $episodeAirDate,
+			"className" => "bg-calendar calendar-item tvID--" . $episodeID,
+			"imagetype" => "tv " . $downloaded,
+			"details" => $details,
+		));
+	}
+	if ($i != 0) {
+		return $gotCalendar;
+	}
 	return false;
 }
+
 function ombiAPI($array)
 {
-    return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type']);
+	return ombiAction($array['data']['id'], $array['data']['action'], $array['data']['type']);
 }
+
 function ombiAction($id, $action, $type)
 {
-    if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
-        $url = qualifyURL($GLOBALS['ombiURL']);
-        $headers = array(
-            "Accept" => "application/json",
-            "Content-Type" => "application/json",
-            "Apikey" => $GLOBALS['ombiToken']
-        );
-        $data = array(
-            'id' => $id,
-        );
-        switch ($type) {
-            case 'season':
-            case 'tv':
-                $type = 'tv';
-                $add = array(
-                    'tvDbId' => $id,
-                    'requestAll' => true,
-                    'latestSeason' => true,
-                    'firstSeason' => true
-                );
-                break;
-            default:
-                $type = 'movie';
-                $add = array("theMovieDbId" => (int)$id);
-                break;
-        }
-        $success['head'] = $headers;
-        $success['act'] = $action;
-        $success['data'] = $data;
-        $success['add'] = $add;
-        $success['type'] = $type;
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            switch ($action) {
-                case 'add':
-                    if (isset($_COOKIE['Auth'])) {
-                        $headers = array(
-                            "Accept" => "application/json",
-                            "Content-Type" => "application/json",
-                            "Authorization" => "Bearer ".$_COOKIE['Auth']
-                        );
-                        $success['head'] = $headers;
-                    } else {
-                        return false;
-                    }
-                    $response = Requests::post($url."/api/v1/Request/".$type, $headers, json_encode($add), $options);
-                    break;
-                default:
-                    if (qualifyRequest(1)) {
-                        switch ($action) {
-                            case 'approve':
-                                $response = Requests::post($url."/api/v1/Request/".$type."/approve", $headers, json_encode($data), $options);
-                                break;
-                            case 'available':
-                                $response = Requests::post($url."/api/v1/Request/".$type."/available", $headers, json_encode($data), $options);
-                                break;
-                            case 'unavailable':
-                                $response = Requests::post($url."/api/v1/Request/".$type."/unavailable", $headers, json_encode($data), $options);
-                                break;
-                            case 'deny':
-                                $response = Requests::put($url."/api/v1/Request/".$type."/deny", $headers, json_encode($data), $options);
-                                break;
-                            case 'delete':
-                                $response = Requests::delete($url."/api/v1/Request/".$type."/".$id, $headers, $options);
-                                break;
-                            default:
-                                return false;
-                            }
-                    }
-                break;
-            }
-            $success['api'] = $response;
-            $success['bd'] = $response->body;
-            $success['hd'] = $response->headers;
-            if ($response->success) {
-                $success['ok'] = true;
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-    }
-    return isset($success['ok']) ? $success : false;
+	if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
+		$url = qualifyURL($GLOBALS['ombiURL']);
+		$headers = array(
+			"Accept" => "application/json",
+			"Content-Type" => "application/json",
+			"Apikey" => $GLOBALS['ombiToken']
+		);
+		$data = array(
+			'id' => $id,
+		);
+		switch ($type) {
+			case 'season':
+			case 'tv':
+				$type = 'tv';
+				$add = array(
+					'tvDbId' => $id,
+					'requestAll' => true,
+					'latestSeason' => true,
+					'firstSeason' => true
+				);
+				break;
+			default:
+				$type = 'movie';
+				$add = array("theMovieDbId" => (int)$id);
+				break;
+		}
+		$success['head'] = $headers;
+		$success['act'] = $action;
+		$success['data'] = $data;
+		$success['add'] = $add;
+		$success['type'] = $type;
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			switch ($action) {
+				case 'add':
+					if (isset($_COOKIE['Auth'])) {
+						$headers = array(
+							"Accept" => "application/json",
+							"Content-Type" => "application/json",
+							"Authorization" => "Bearer " . $_COOKIE['Auth']
+						);
+						$success['head'] = $headers;
+					} else {
+						return false;
+					}
+					$response = Requests::post($url . "/api/v1/Request/" . $type, $headers, json_encode($add), $options);
+					break;
+				default:
+					if (qualifyRequest(1)) {
+						switch ($action) {
+							case 'approve':
+								$response = Requests::post($url . "/api/v1/Request/" . $type . "/approve", $headers, json_encode($data), $options);
+								break;
+							case 'available':
+								$response = Requests::post($url . "/api/v1/Request/" . $type . "/available", $headers, json_encode($data), $options);
+								break;
+							case 'unavailable':
+								$response = Requests::post($url . "/api/v1/Request/" . $type . "/unavailable", $headers, json_encode($data), $options);
+								break;
+							case 'deny':
+								$response = Requests::put($url . "/api/v1/Request/" . $type . "/deny", $headers, json_encode($data), $options);
+								break;
+							case 'delete':
+								$response = Requests::delete($url . "/api/v1/Request/" . $type . "/" . $id, $headers, $options);
+								break;
+							default:
+								return false;
+						}
+					}
+					break;
+			}
+			$success['api'] = $response;
+			$success['bd'] = $response->body;
+			$success['hd'] = $response->headers;
+			if ($response->success) {
+				$success['ok'] = true;
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+	}
+	return isset($success['ok']) ? $success : false;
 }
+
 function getOmbiRequests($type = "both")
 {
-    if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
-        $url = qualifyURL($GLOBALS['ombiURL']);
-        $headers = array(
-            "Accept" => "application/json",
-            "Apikey" => $GLOBALS['ombiToken'],
-        );
-        $requests = array();
-        try {
-            $options = (localURL($url)) ? array('verify' => false ) : array();
-            switch ($type) {
-                case 'movie':
-                    $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
-                    break;
-                case 'tv':
-                    $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
-                    break;
+	if ($GLOBALS['homepageOmbiEnabled'] && !empty($GLOBALS['ombiURL']) && !empty($GLOBALS['ombiToken']) && qualifyRequest($GLOBALS['homepageOmbiAuth'])) {
+		$url = qualifyURL($GLOBALS['ombiURL']);
+		$headers = array(
+			"Accept" => "application/json",
+			"Apikey" => $GLOBALS['ombiToken'],
+		);
+		$requests = array();
+		try {
+			$options = (localURL($url)) ? array('verify' => false) : array();
+			switch ($type) {
+				case 'movie':
+					$movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
+					break;
+				case 'tv':
+					$tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
+					break;
+				
+				default:
+					$movie = Requests::get($url . "/api/v1/Request/movie", $headers, $options);
+					$tv = Requests::get($url . "/api/v1/Request/tv", $headers, $options);
+					break;
+			}
+			if ($movie->success || $tv->success) {
+				if (isset($movie)) {
+					$movie = json_decode($movie->body, true);
+					//$movie = array_reverse($movie);
+					foreach ($movie as $key => $value) {
+						$requests[] = array(
+							'test' => $value,
+							'id' => $value['theMovieDbId'],
+							'title' => $value['title'],
+							'overview' => $value['overview'],
+							'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/' . $value['posterPath'] : '',
+							'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
+							'approved' => $value['approved'],
+							'available' => $value['available'],
+							'denied' => $value['denied'],
+							'deniedReason' => $value['deniedReason'],
+							'user' => $value['requestedUser']['userName'],
+							'request_id' => $value['id'],
+							'request_date' => $value['requestedDate'],
+							'release_date' => $value['releaseDate'],
+							'type' => 'movie',
+							'icon' => 'mdi mdi-filmstrip',
+							'color' => 'palette-Deep-Purple-900 bg white',
+						);
+					}
+				}
+				if (isset($tv) && (is_array($tv) || is_object($tv))) {
+					$tv = json_decode($tv->body, true);
+					foreach ($tv as $key => $value) {
+						if (is_array($value['childRequests'][0])) {
+							$requests[] = array(
+								'test' => $value,
+								'id' => $value['tvDbId'],
+								'title' => $value['title'],
+								'overview' => $value['overview'],
+								'poster' => $value['posterPath'],
+								'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/' . $value['background'] : '',
+								'approved' => $value['childRequests'][0]['approved'],
+								'available' => $value['childRequests'][0]['available'],
+								'denied' => $value['childRequests'][0]['denied'],
+								'deniedReason' => $value['childRequests'][0]['deniedReason'],
+								'user' => $value['childRequests'][0]['requestedUser']['userName'],
+								'request_id' => $value['id'],
+								'request_date' => $value['childRequests'][0]['requestedDate'],
+								'release_date' => $value['releaseDate'],
+								'type' => 'tv',
+								'icon' => 'mdi mdi-television',
+								'color' => 'grayish-blue-bg',
+							);
+						}
+					}
+				}
+				//sort here
+				usort($requests, function ($item1, $item2) {
+					if ($item1['request_date'] == $item2['request_date']) {
+						return 0;
+					}
+					return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
+				});
+			}
+		} catch (Requests_Exception $e) {
+			writeLog('error', 'OMBI Connect Function - Error: ' . $e->getMessage(), 'SYSTEM');
+		};
+	}
+	$api['content'] = isset($requests) ? $requests : false;
+	return $api;
+}
 
-                default:
-                    $movie = Requests::get($url."/api/v1/Request/movie", $headers, $options);
-                    $tv = Requests::get($url."/api/v1/Request/tv", $headers, $options);
-                    break;
-            }
-            if ($movie->success || $tv->success) {
-                if (isset($movie)) {
-                    $movie = json_decode($movie->body, true);
-                    //$movie = array_reverse($movie);
-                    foreach ($movie as $key => $value) {
-                        $requests[] = array(
-                            'test' => $value,
-                            'id' => $value['theMovieDbId'],
-                            'title' => $value['title'],
-                            'overview' => $value['overview'],
-                            'poster' => (isset($value['posterPath']) && $value['posterPath'] !== '') ? 'https://image.tmdb.org/t/p/w300/'.$value['posterPath'] : '',
-                            'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
-                            'approved' => $value['approved'],
-                            'available' => $value['available'],
-                            'denied' => $value['denied'],
-                            'deniedReason' => $value['deniedReason'],
-                            'user' => $value['requestedUser']['userName'],
-                            'request_id' => $value['id'],
-                            'request_date' => $value['requestedDate'],
-                            'release_date' => $value['releaseDate'],
-                            'type' => 'movie',
-                            'icon' => 'mdi mdi-filmstrip',
-                            'color' => 'palette-Deep-Purple-900 bg white',
-                        );
-                    }
-                }
-                if (isset($tv) && (is_array($tv) || is_object($tv))) {
-                    $tv = json_decode($tv->body, true);
-                    foreach ($tv as $key => $value) {
-                        if (is_array($value['childRequests'][0])) {
-                            $requests[] = array(
-                                'test' => $value,
-                                'id' => $value['tvDbId'],
-                                'title' => $value['title'],
-                                'overview' => $value['overview'],
-                                'poster' => $value['posterPath'],
-                                'background' => (isset($value['background']) && $value['background'] !== '') ? 'https://image.tmdb.org/t/p/w1280/'.$value['background'] : '',
-                                'approved' => $value['childRequests'][0]['approved'],
-                                'available' => $value['childRequests'][0]['available'],
-                                'denied' => $value['childRequests'][0]['denied'],
-                                'deniedReason' => $value['childRequests'][0]['deniedReason'],
-                                'user' => $value['childRequests'][0]['requestedUser']['userName'],
-                                'request_id' => $value['id'],
-                                'request_date' => $value['childRequests'][0]['requestedDate'],
-                                'release_date' => $value['releaseDate'],
-                                'type' => 'tv',
-                                'icon' => 'mdi mdi-television',
-                                'color' => 'grayish-blue-bg',
-                            );
-                        }
-                    }
-                }
-                //sort here
-                usort($requests, function ($item1, $item2) {
-                    if ($item1['request_date'] == $item2['request_date']) {
-                        return 0;
-                    }
-                    return $item1['request_date'] > $item2['request_date'] ? -1 : 1;
-                });
-            }
-        } catch (Requests_Exception $e) {
-            writeLog('error', 'OMBI Connect Function - Error: '.$e->getMessage(), 'SYSTEM');
-        };
-    }
-    $api['content'] = isset($requests) ? $requests : false;
-    return $api;
+function testAPIConnection($array)
+{
+	switch ($array['data']['action']) {
+		case 'plex':
+			if (!empty($GLOBALS['plexURL']) && !empty($GLOBALS['plexToken'])) {
+				$url = qualifyURL($GLOBALS['plexURL']);
+				$url = $url . "/?X-Plex-Token=" . $GLOBALS['plexToken'];
+				try {
+					$options = (localURL($url)) ? array('verify' => false) : array();
+					$response = Requests::get($url, array(), $options);
+					libxml_use_internal_errors(true);
+					if ($response->success) {
+						return true;
+					}
+				} catch (Requests_Exception $e) {
+					return $e->getMessage();
+				};
+			}else{
+				return 'URL and/or Token not setup';
+			}
+			break;
+		case 'emby':
+			
+			break;
+		case 'sonarr':
+			if (!empty($GLOBALS['sonarrURL']) && !empty($GLOBALS['sonarrToken'])) {
+				$sonarrs = array();
+				$sonarrURLList = explode(',', $GLOBALS['sonarrURL']);
+				$sonarrTokenList = explode(',', $GLOBALS['sonarrToken']);
+				if (count($sonarrURLList) == count($sonarrTokenList)) {
+					foreach ($sonarrURLList as $key => $value) {
+						$sonarrs[$key] = array(
+							'url' => $value,
+							'token' => $sonarrTokenList[$key]
+						);
+					}
+					foreach ($sonarrs as $key => $value) {
+						try {
+							$sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
+							$sonarr->getSystemStatus();
+							return true;
+						} catch (Exception $e) {
+							return $e->getMessage();
+						}
+					}
+				}
+			}else{
+				return 'URL/s and/or Token/s not setup';
+			}
+			break;
+		case 'radarr':
+			if (!empty($GLOBALS['radarrURL']) && !empty($GLOBALS['radarrToken'])) {
+				$sonarrs = array();
+				$sonarrURLList = explode(',', $GLOBALS['radarrURL']);
+				$sonarrTokenList = explode(',', $GLOBALS['radarrToken']);
+				if (count($sonarrURLList) == count($sonarrTokenList)) {
+					foreach ($sonarrURLList as $key => $value) {
+						$sonarrs[$key] = array(
+							'url' => $value,
+							'token' => $sonarrTokenList[$key]
+						);
+					}
+					foreach ($sonarrs as $key => $value) {
+						try {
+							$sonarr = new Kryptonit3\Sonarr\Sonarr($value['url'], $value['token']);
+							$sonarr->getSystemStatus();
+							return true;
+						} catch (Exception $e) {
+							return $e->getMessage();
+						}
+					}
+				}
+			}else{
+				return 'URL/s and/or Token/s not setup';
+			}
+			break;
+		case 'sabnzbd':
+			if (!empty($GLOBALS['sabnzbdURL']) && !empty($GLOBALS['sabnzbdToken']) ) {
+				$url = qualifyURL($GLOBALS['sabnzbdURL']);
+				$url = $url . '/api?mode=queue&output=json&apikey=' . $GLOBALS['sabnzbdToken'];
+				try {
+					$options = (localURL($url)) ? array('verify' => false) : array();
+					$response = Requests::get($url, array(), $options);
+					if ($response->success) {
+						return true;
+					}
+				} catch (Requests_Exception $e) {
+					return $e->getMessage();
+				};
+			}else{
+				return 'URL and/or Token not setup';
+			}
+			break;
+		case 'nzbget':
+			if (!empty($GLOBALS['nzbgetURL']) && !empty($GLOBALS['nzbgetUsername']) && !empty($GLOBALS['nzbgetPassword'])) {
+				$url = qualifyURL($GLOBALS['nzbgetURL']);
+				$url = $url . '/' . $GLOBALS['nzbgetUsername'] . ':' . decrypt($GLOBALS['nzbgetPassword']) . '/jsonrpc/listgroups';
+				try {
+					$options = (localURL($url)) ? array('verify' => false) : array();
+					$response = Requests::get($url, array(), $options);
+					if ($response->success) {
+						return true;
+					}
+				} catch (Requests_Exception $e) {
+					return $e->getMessage();
+				};
+			}else{
+				return 'URL and/or Username/Password not setup';
+			}
+			break;
+		case 'deluge':
+			if (!empty($GLOBALS['delugeURL']) && !empty($GLOBALS['delugePassword'])) {
+				try {
+					
+					$deluge = new deluge($GLOBALS['delugeURL'], decrypt($GLOBALS['delugePassword']));
+					$torrents = $deluge->getTorrents(null, 'comment, download_payload_rate, eta, hash, is_finished, is_seed, message, name, paused, progress, queue, state, total_size, upload_payload_rate');
+					return true;
+				} catch (\Excecption $e) {
+					return $e->getMessage();
+				}
+			}
+			else{
+				return 'URL and/or Password not setup';
+			}
+			break;
+		default :
+			return false;
+	}
+	return false;
 }

+ 90 - 6
api/functions/homepage-functions.php

@@ -578,7 +578,21 @@ function getHomepageList()
                         'value' => $GLOBALS['plexTabURL'],
                         'placeholder' => 'http(s)://hostname:port'
                     )
-                )
+                ),
+	            'Test Connection' => array(
+	            	array(
+	            		'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'plex\')"'
+		            ),
+	            )
             )
         ),
         array(
@@ -736,7 +750,21 @@ function getHomepageList()
                         'value' => $GLOBALS['homepageDownloadRefresh'],
                         'options' => $time
                     )
-                )
+                ),
+	            'Test Connection' => array(
+		            array(
+			            'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'sabnzbd\')"'
+		            ),
+	            )
             )
         ),
         array(
@@ -789,7 +817,21 @@ function getHomepageList()
                         'value' => $GLOBALS['homepageDownloadRefresh'],
                         'options' => $time
                     )
-                )
+                ),
+	            'Test Connection' => array(
+		            array(
+			            'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'nzbget\')"'
+		            ),
+	            )
             )
         ),
         array(
@@ -1007,7 +1049,21 @@ function getHomepageList()
                         'value' => $GLOBALS['homepageDownloadRefresh'],
                         'options' => $time
                     )
-                )
+                ),
+	            'Test Connection' => array(
+		            array(
+			            'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'deluge\')"'
+		            ),
+	            )
             )
         ),
         array(
@@ -1096,7 +1152,21 @@ function getHomepageList()
                         'value' => $GLOBALS['calendarRefresh'],
                         'options' => $time
                     )
-                )
+                ),
+	            'Test Connection' => array(
+		            array(
+			            'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'sonarr\')"'
+		            ),
+	            )
             )
         ),
         array(
@@ -1185,7 +1255,21 @@ function getHomepageList()
                         'value' => $GLOBALS['calendarRefresh'],
                         'options' => $time
                     )
-                )
+                ),
+	            'Test Connection' => array(
+		            array(
+			            'type' => 'blank',
+			            'label' => ''
+		            ),
+		            array(
+			            'type' => 'button',
+			            'label' => '',
+			            'icon' => 'fa fa-flask',
+			            'class' => 'pull-right',
+			            'text' => 'Test Connection',
+			            'attr' => 'onclick="testAPIConnection(\'radarr\')"'
+		            ),
+	            )
             )
         ),
         array(

Rozdielové dáta súboru neboli zobrazené, pretože súbor je príliš veľký
+ 523 - 510
api/functions/organizr-functions.php


+ 19 - 0
api/index.php

@@ -324,6 +324,25 @@ switch ($function) {
                 break;
         }
         break;
+	case 'v1_test_api_connection':
+		switch ($method) {
+			case 'POST':
+				if (qualifyRequest(1)) {
+					$result['status'] = 'success';
+					$result['statusText'] = 'success';
+					$result['data'] = testAPIConnection($_POST);
+				} else {
+					$result['status'] = 'error';
+					$result['statusText'] = 'API/Token invalid or not set';
+					$result['data'] = null;
+				}
+				break;
+			default:
+				$result['status'] = 'error';
+				$result['statusText'] = 'The function requested is not defined for method: '.$method;
+				break;
+		}
+		break;
     case 'v1_settings_tab_editor_tabs':
         switch ($method) {
             case 'GET':

+ 16 - 1
js/functions.js

@@ -198,7 +198,7 @@ function noTabs(arrayItems){
 	}
 }
 function logout(){
-	message('',' Goodbye!','bottom-right','#FFF','success','10000')
+	message('',' Goodbye!','bottom-right','#FFF','success','10000');
 	organizrAPI('GET','api/?v1/logout').success(function(data) {
 		var html = JSON.parse(data);
 		if(html.data == true){
@@ -3459,6 +3459,21 @@ function homepageRequests(timeout){
 	if(typeof timeouts['ombi'] !== 'undefined'){ clearTimeout(timeouts['ombi']); }
 	timeouts['ombi'] = setTimeout(function(){ homepageRequests(timeout); }, timeout);
 }
+function testAPIConnection(service){
+    messageSingle('',' Testing now...','bottom-right','#FFF','success','10000');
+    organizrAPI('POST','api/?v1/test/api/connection',{action:service}).success(function(data) {
+        var response = JSON.parse(data);
+        if(response.data == true){
+            messageSingle('',' API Connection Success','bottom-right','#FFF','success','10000');
+        }else{
+            messageSingle('API Connection Failed',response.data,'bottom-right','#FFF','error','10000');
+        }
+        console.log(response);
+    }).fail(function(xhr) {
+        console.error("Organizr Function: API Connection Failed");
+        message('',' Organizr Error','bottom-right','#FFF','error','10000');
+    });
+}
 function homepageCalendar(timeout){
 	var timeout = (typeof timeout !== 'undefined') ? timeout : activeInfo.settings.homepage.refresh.calendarRefresh;
     if(activeInfo.settings.homepage.options.alternateHomepageHeaders){

Niektoré súbory nie sú zobrazené, pretože je v týchto rozdielových dátach zmenené mnoho súborov