Skip to content

Commit

Permalink
Merge branch 'develop' into add-anidex
Browse files Browse the repository at this point in the history
  • Loading branch information
medariox authored May 7, 2017
2 parents 50e9e6a + 89cab43 commit a10602a
Show file tree
Hide file tree
Showing 27 changed files with 972 additions and 491 deletions.
10 changes: 7 additions & 3 deletions lib/tvdbapiv2/auth/tvdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from time import time
import requests
from requests.compat import urljoin

from .jwt import JWTBearerAuth
from ..exceptions import AuthError
Expand All @@ -21,10 +22,11 @@ class TVDBAuth(JWTBearerAuth):

refresh_window = 7200 # seconds

def __init__(self, api_key=None, token=None):
def __init__(self, api_key=None, token=None, api_base='https://api.thetvdb.com'):
"""Create a new TVDB request auth."""
super(TVDBAuth, self).__init__(token)
self.api_key = api_key
self.api_base = api_base

@property
def authorization(self):
Expand Down Expand Up @@ -64,8 +66,9 @@ def login(self):
if not self.api_key:
raise AuthError('Missing API key')
response = requests.post(
'https://api.thetvdb.com/login',
urljoin(self.api_base, 'login'),
json=self.authorization,
verify=False,
)
try:
self._get_token(response)
Expand All @@ -85,8 +88,9 @@ def refresh(self):
return self.login()

response = requests.get(
'https://api.thetvdb.com/refresh_token',
urljoin(self.api_base, 'refresh_token'),
headers=self.auth_header,
verify=False,
)

try:
Expand Down
8 changes: 8 additions & 0 deletions medusa/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,10 @@ def initialize(self, console_logging=True):
app.BACKLOG_PERIOD = check_setting_str(app.CFG, 'GUI', 'backlog_period', 'all')
app.BACKLOG_STATUS = check_setting_str(app.CFG, 'GUI', 'backlog_status', 'all')

app.FALLBACK_PLEX_ENABLE = check_setting_int(app.CFG, 'General', 'fallback_plex_enable', 1)
app.FALLBACK_PLEX_NOTIFICATIONS = check_setting_int(app.CFG, 'General', 'fallback_plex_notifications', 1)
app.FALLBACK_PLEX_TIMEOUT = check_setting_int(app.CFG, 'General', 'fallback_plex_timeout', 3)

# reconfigure the logger
app_logger.reconfigure()

Expand Down Expand Up @@ -1481,6 +1485,10 @@ def save_config():
new_config['General']['backlog_period'] = app.BACKLOG_PERIOD
new_config['General']['backlog_status'] = app.BACKLOG_STATUS

new_config['General']['fallback_plex_enable'] = app.FALLBACK_PLEX_ENABLE
new_config['General']['fallback_plex_notifications'] = app.FALLBACK_PLEX_NOTIFICATIONS
new_config['General']['fallback_plex_timeout'] = app.FALLBACK_PLEX_TIMEOUT

new_config['Blackhole'] = {}
new_config['Blackhole']['nzb_dir'] = app.NZB_DIR
new_config['Blackhole']['torrent_dir'] = app.TORRENT_DIR
Expand Down
7 changes: 7 additions & 0 deletions medusa/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,3 +614,10 @@
'45m': '45 mins',
'15m': '15 mins'
}

# Plex fallback settings
FALLBACK_PLEX_ENABLE = True
FALLBACK_PLEX_NOTIFICATIONS = True
FALLBACK_PLEX_TIMEOUT = 3
FALLBACK_PLEX_API_URL = 'https://tvdb2.plex.tv'
TVDB_API_KEY = '0629B785CE550C8D'
2 changes: 1 addition & 1 deletion medusa/helpers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ def hardlink_file(src_file, dest_file):
u'Failed to create hardlink of {source} at {destination}.'
u' Error: {error!r}. Copying instead', {
'source': src_file,
'dest': dest_file,
'destination': dest_file,
'error': msg,
}
)
Expand Down
34 changes: 32 additions & 2 deletions medusa/helpers/externals.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

import logging

from medusa import app
from medusa import app, db
from medusa.indexers.indexer_api import indexerApi
from medusa.indexers.indexer_config import indexerConfig
from medusa.indexers.indexer_config import indexerConfig, mappings
from medusa.indexers.indexer_exceptions import IndexerException, IndexerShowAllreadyInLibrary, IndexerUnavailable
from medusa.logger.adapters.style import BraceAdapter

Expand Down Expand Up @@ -166,3 +166,33 @@ def check_existing_shows(indexed_show, indexer):
'Please remove the show, before you can add it through {2}.'
.format(show.name, indexerApi(show.indexer).name,
indexerApi(indexer).name))


def load_externals_from_db(indexer=None, indexer_id=None):
"""Load and recreate the indexers external id's.
:param indexer: Optional pass indexer id, else use the current shows indexer.
:type indexer: int
:param indexer_id: Optional pass indexer id, else use the current shows indexer.
:type indexer_id: int
"""
externals = {}

main_db_con = db.DBConnection()
sql = (b'SELECT indexer, indexer_id, mindexer, mindexer_id '
b'FROM indexer_mapping '
b'WHERE (indexer = ? AND indexer_id = ?) '
b'OR (mindexer = ? AND mindexer_id = ?)')

results = main_db_con.select(sql, [indexer, indexer_id, indexer, indexer_id])

for result in results:
try:
if result[b'indexer'] == indexer:
externals[mappings[result[b'mindexer']]] = result[b'mindexer_id']
else:
externals[mappings[result[b'indexer']]] = result[b'indexer_id']
except KeyError as e:
log.error(u'Indexer not supported in current mappings: {id}', {'id': e.message})

return externals
2 changes: 1 addition & 1 deletion medusa/image_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def which_type(self, image_path):
try:
os.remove(image_path)
except OSError as e:
logger.log("Could't delete file: {image_path}. Please manually delete it. Error: {error_msg}".format
logger.log("Couldn't delete file: {image_path}. Please manually delete it. Error: {error_msg}".format
(image_path=image_path, error_msg=e), logger.WARNING)
return

Expand Down
9 changes: 6 additions & 3 deletions medusa/indexers/indexer_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.

import os
from .indexer_config import indexerConfig, initConfig
from .. import app
from ..helper.common import try_int

from medusa import app
from medusa.helper.common import try_int
from medusa.indexers.indexer_config import indexerConfig, initConfig
from medusa.indexers.tvdbv2.fallback import PlexFallBackConfig


class indexerApi(object):
Expand All @@ -29,6 +31,7 @@ def __init__(self, indexer_id=None):
def __del__(self):
pass

@PlexFallBackConfig
def indexer(self, *args, **kwargs):
if self.indexer_id:
return indexerConfig[self.indexer_id]['module'](*args, **kwargs)
Expand Down
16 changes: 0 additions & 16 deletions medusa/indexers/indexer_config.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
# coding=utf-8
# Author: p0psicles
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Medusa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.

import re

Expand Down
16 changes: 0 additions & 16 deletions medusa/indexers/indexer_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
# coding=utf-8
# Author: p0psicles
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Medusa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.

"""Custom exceptions used or raised by indexer_api."""

Expand Down
38 changes: 10 additions & 28 deletions medusa/indexers/indexer_ui.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
# coding=utf-8
# Author: p0psicles
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Medusa is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Medusa. If not, see <http://www.gnu.org/licenses/>.

"""Contains included user interface for TVmaze show selection."""

Expand All @@ -23,14 +7,12 @@

from indexer_exceptions import IndexerUserAbort


__author__ = 'p0psicles'
__version__ = '1.0'


def log():
"""Get logging object."""
return logging.getLogger(__name__)
log = logging.getLogger(__name__)
log.logger.addHandler(logging.NullHandler())


class BaseUI(object):
Expand Down Expand Up @@ -63,14 +45,14 @@ def _display_series(self, all_series, limit=6):
print 'Show Search Results:'
for i, cshow in enumerate(toshow):
i_show = i + 1 # Start at more human readable number 1 (not 0)
log().debug('Showing all_series[%s], series %s)', i_show, all_series[i]['seriesname'])
log.debug('Showing all_series[{0}], series {1})', i_show, all_series[i]['seriesname'])
if i == 0:
extra = ' (default)'
else:
extra = ''

# TODO: Change into something more generic.
print '%s -> %s [%s] # http://thetvdb.com/?tab=series&id=%s&lid=%s%s' % (
print '{0} -> {1} [{2}] # http://thetvdb.com/?tab=series&id={3}&lid={4}{5}'.format(
i_show,
cshow['seriesname'].encode('UTF-8', 'ignore'),
cshow['language'].encode('UTF-8', 'ignore'),
Expand Down Expand Up @@ -101,16 +83,16 @@ def select_series(self, all_series):
except EOFError:
raise IndexerUserAbort('User aborted (EOF received)')

log().debug('Got choice of: %s', ans)
log.debug('Got choice of: {0}', ans)
try:
selected_id = int(ans) - 1 # The human entered 1 as first result, not zero
except ValueError: # Input was not number
if len(ans.strip()) == 0:
# Default option
log().debug('Default option, returning first series')
log.debug('Default option, returning first series')
return all_series[0]
if ans == 'q':
log().debug('Got quit command (q)')
log.debug('Got quit command (q)')
raise IndexerUserAbort("User aborted ('q' quit command)")
elif ans == '?':
print '## Help'
Expand All @@ -123,12 +105,12 @@ def select_series(self, all_series):
elif ans.lower() in ['a', 'all']:
self._display_series(all_series, limit=None)
else:
log().debug('Unknown keypress %s', ans)
log.debug('Unknown keypress {0}', ans)
else:
log().debug('Trying to return ID: %d', selected_id)
log.debug('Trying to return ID: {0}', selected_id)
try:
return all_series[selected_id]
except IndexError:
log().debug('Invalid show number entered!')
log.debug('Invalid show number entered!')
print 'Invalid number (%s) selected!'
self._display_series(all_series)
Loading

0 comments on commit a10602a

Please sign in to comment.