Passed
Push — develop ( c6fa42...950d5f )
by Dean
02:50
created

RestartRequired()   A

Complexity

Conditions 4

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.2
cc 4
1
# ------------------------------------------------
2
# Environment
3
# ------------------------------------------------
4
from plugin.core.environment import Environment, translate as _
5
import os
6
7
Environment.setup(Core, Dict, Platform, Prefs)
8
9
# plex.database.py
10
os.environ['LIBRARY_DB'] = os.path.join(
11
    Environment.path.plugin_support, 'Databases',
12
    'com.plexapp.plugins.library.db'
13
)
14
15
# ------------------------------------------------
16
# FS Migrator
17
# ------------------------------------------------
18
from fs_migrator import FSMigrator
19
20
FSMigrator.run()
21
22
# ------------------------------------------------
23
# Logger
24
# ------------------------------------------------
25
26
from plugin.core.logger import LoggerManager
27
28
LoggerManager.setup(storage=False)
29
30
# ------------------------------------------------
31
# Interface messages
32
# ------------------------------------------------
33
34
from plugin.core.message import InterfaceMessages
35
36
InterfaceMessages.bind()
37
38
# ------------------------------------------------
39
# Language
40
# ------------------------------------------------
41
Environment.setup_locale()
42
Environment.setup_translation()
43
# ------------------------------------------------
44
# Libraries
45
# ------------------------------------------------
46
from plugin.core.libraries.manager import LibrariesManager
47
48
LibrariesManager.setup(cache=True)
49
LibrariesManager.test()
50
# ------------------------------------------------
51
# Warnings
52
# ------------------------------------------------
53
from requests.packages.urllib3.exceptions import InsecurePlatformWarning, SNIMissingWarning
54
import warnings
55
56
warnings.filterwarnings('once', category=InsecurePlatformWarning)
57
warnings.filterwarnings('once', category=SNIMissingWarning)
58
# ------------------------------------------------
59
# Modules
60
# ------------------------------------------------
61
import core
62
import interface
63
# ------------------------------------------------
64
# Handlers
65
# ------------------------------------------------
66
from interface.m_main import MainMenu
67
from interface.resources import Cover, Thumb
68
# ------------------------------------------------
69
70
# Local imports
71
from core.logger import Logger
72
from core.helpers import spawn
73
from main import Main
74
75
from plugin.api.core.manager import ApiManager
76
from plugin.core.constants import PLUGIN_NAME, PLUGIN_ART, PLUGIN_ICON, PLUGIN_IDENTIFIER
77
from plugin.core.singleton import Singleton
78
from plugin.models.account import Account
79
from plugin.modules.migrations.account import AccountMigration
80
from plugin.preferences import Preferences
81
82
from datetime import datetime
83
from plex import Plex
84
import json
85
import time
86
87
# http://bugs.python.org/issue7980
88
datetime.strptime('', '')
89
90
log = Logger()
91
92
93
def Start():
94
    ObjectContainer.art = R(PLUGIN_ART)
95
    ObjectContainer.title1 = PLUGIN_NAME
96
    DirectoryObject.thumb = R(PLUGIN_ICON)
97
    DirectoryObject.art = R(PLUGIN_ART)
98
    PopupDirectoryObject.thumb = R(PLUGIN_ICON)
99
    PopupDirectoryObject.art = R(PLUGIN_ART)
100
101
    if not Singleton.acquire():
102
        log.warn('Unable to acquire plugin instance')
103
104
    # Complete logger initialization
105
    LoggerManager.setup(storage=True)
106
107
    # Store current proxy details
108
    Dict['proxy_host'] = Prefs['proxy_host']
109
110
    Dict['proxy_username'] = Prefs['proxy_username']
111
    Dict['proxy_password'] = Prefs['proxy_password']
112
113
    # Store current language
114
    Dict['language'] = Prefs['language']
115
116
    # Start plugin
117
    m = Main()
118
    m.start()
119
120
121
@expose
122
def Api(*args, **kwargs):
123
    try:
124
        data = ApiManager.process(
125
            Request.Method,
126
            Request.Headers,
127
            Request.Body,
128
129
            *args, **kwargs
130
        )
131
132
        return json.dumps(data)
133
    except Exception as ex:
134
        Log.Error('Unable to process API request (args: %r, kwargs: %r) - %s', args, kwargs, ex)
135
        return None
136
137
138
def ValidatePrefs():
139
    # Retrieve plex token
140
    token_plex = AccountMigration.get_token(Request.Headers)
141
142
    # Retrieve current activity mode
143
    last_activity_mode = Preferences.get('activity.mode')
144
145
    if Request.Headers.get('X-Disable-Preference-Migration', '0') == '0':
146
        # Run account migration
147
        am = AccountMigration()
148
        am.run(token_plex)
149
150
        # Migrate server preferences
151
        Preferences.migrate()
152
153
        # Try migrate administrator preferences
154
        try:
155
            Preferences.initialize(account=1)
156
            Preferences.migrate(account=1)
157
        except Account.DoesNotExist:
158
            log.debug('Unable to migrate administrator preferences, no account found')
159
    else:
160
        log.debug('Ignoring preference migration (disabled by header)')
161
162
    # Restart if activity_mode has changed
163
    if RestartRequired(last_activity_mode):
164
        log.info('Restart required to apply changes, restarting plugin...')
165
166
        def restart():
167
            # Delay until after `ValidatePrefs` returns
168
            time.sleep(3)
169
170
            # Restart plugin
171
            Plex[':/plugins'].restart(PLUGIN_IDENTIFIER)
172
173
        spawn(restart, daemon=True)
174
        return MessageContainer(_("Success"), _("Success"))
175
176
    # Fire configuration changed callback
177
    spawn(Main.on_configuration_changed, daemon=True)
178
179
    return MessageContainer(_("Success"), _("Success"))
180
181
182
def RestartRequired(last_activity_mode):
183
    if Preferences.get('activity.mode') != last_activity_mode:
184
        return True
185
186
    for key in ['language', 'proxy_host', 'proxy_username', 'proxy_password']:
187
        if Prefs[key] != Dict[key]:
188
            return True
189
190
    return False
191