forked from l3uddz/plex_autoscan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
258 lines (221 loc) · 8.1 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import argparse
import json
import logging
import os
import sys
import uuid
logger = logging.getLogger("CONFIG")
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Config(object):
__metaclass__ = Singleton
base_config = {
'PLEX_USER': 'plex',
'PLEX_SECTION_PATH_MAPPINGS': {
'1': [
'/Movies/'
],
'2': [
'/TV/'
]
},
'PLEX_SCANNER': '/usr/lib/plexmediaserver/Plex\\ Media\\ Scanner',
'PLEX_SUPPORT_DIR': '/var/lib/plexmediaserver/Library/Application\ Support',
'PLEX_LD_LIBRARY_PATH': '/usr/lib/plexmediaserver',
'PLEX_DATABASE_PATH': '/var/lib/plexmediaserver/Library/Application Support/Plex Media Server'
'/Plug-in Support/Databases/com.plexapp.plugins.library.db',
'PLEX_LOCAL_URL': 'http://localhost:32400',
'PLEX_EMPTY_TRASH': False,
'PLEX_EMPTY_TRASH_MAX_FILES': 100,
'PLEX_EMPTY_TRASH_CONTROL_FILES': [
'/mnt/unionfs/mounted.bin'
],
'PLEX_EMPTY_TRASH_ZERO_DELETED': False,
'PLEX_WAIT_FOR_EXTERNAL_SCANNERS': True,
'PLEX_ANALYZE_FILE_TYPE': 'basic',
'PLEX_TOKEN': '',
'SERVER_IP': '0.0.0.0',
'SERVER_PORT': 3467,
'SERVER_PASS': uuid.uuid4().hex,
'SERVER_PATH_MAPPINGS': {
'/mnt/unionfs': [
'/home/seed/media/fused'
]
},
'SERVER_SCAN_DELAY': 5,
'SERVER_MAX_FILE_CHECKS': 10,
'SERVER_FILE_EXIST_PATH_MAPPINGS': {
'/home/thompsons/plexdrive': [
'/data'
]
},
'SERVER_ALLOW_MANUAL_SCAN': False,
'SERVER_IGNORE_LIST': [
'/.grab/',
'.DS_Store',
'Thumbs.db'
],
'SERVER_USE_SQLITE': False,
'SERVER_SCAN_PRIORITIES': {
0: [
'/Movies/'
],
1: [
'/TV/'
],
2: [
'/Music/'
]
},
'RCLONE_RC_CACHE_EXPIRE': {
'ENABLED': False,
'MOUNT_FOLDER': '/mnt/rclone',
'RC_URL': 'http://localhost:5572'
},
'DOCKER_NAME': 'plex',
'RUN_COMMAND_BEFORE_SCAN': '',
'USE_DOCKER': False,
'USE_SUDO': True
}
base_settings = {
'config': {
'argv': '--config',
'env': 'PLEX_AUTOSCAN_CONFIG',
'default': os.path.join(os.path.dirname(sys.argv[0]), 'config', 'config.json')
},
'logfile': {
'argv': '--logfile',
'env': 'PLEX_AUTOSCAN_LOGFILE',
'default': os.path.join(os.path.dirname(sys.argv[0]), 'plex_autoscan.log')
},
'loglevel': {
'argv': '--loglevel',
'env': 'PLEX_AUTOSCAN_LOGLEVEL',
'default': 'INFO'
},
'queuefile': {
'argv': '--queuefile',
'env': 'PLEX_AUTOSCAN_QUEUEFILE',
'default': os.path.join(os.path.dirname(sys.argv[0]), 'queue.db')
}
}
def __init__(self):
"""Initializes config"""
# Args and settings
self.args = self.parse_args()
self.settings = self.get_settings()
# Configs
self.configs = None
def upgrade(self, cfg):
fields = []
fields_env = {}
# ENV gets priority: ENV < config.json
for name, data in self.base_config.items():
if name not in cfg:
cfg[name] = data
fields.append(name)
if name in os.environ:
# Use JSON decoder to get same behaviour as config file
fields_env[name] = json.JSONDecoder().decode(os.environ[name])
logger.info("Using ENV setting %s=%s", name, fields_env[name])
# Only rewrite config file if new fields added
if len(fields):
logger.warn("Upgraded config, added %d new field(s): %r", len(fields), fields)
self.save(cfg)
# Update in-memory config with environment settings
cfg.update(fields_env)
return cfg
def load(self):
if not os.path.exists(self.settings['config']):
logger.warn("No config file found, creating default config.")
self.save(self.base_config)
cfg = {}
with open(self.settings['config'], 'r') as fp:
cfg = self.upgrade(json.load(fp))
self.configs = cfg
def save(self, cfg):
with open(self.settings['config'], 'w') as fp:
json.dump(cfg, fp, indent=2, sort_keys=True)
logger.warn(
"Please configure/review config before running again: %r",
self.settings['config']
)
exit(0)
def get_settings(self):
setts = {}
for name, data in self.base_settings.items():
# Argrument priority: cmd < environment < default
try:
value = None
# Command line argument
if self.args[name]:
value = self.args[name]
logger.info("Using ARG setting %s=%s", name, value)
# Envirnoment variable
elif data['env'] in os.environ:
value = os.environ[data['env']]
logger.info("Using ENV setting %s=%s" % (
data['env'],
value
))
# Default
else:
value = data['default']
logger.info("Using default setting %s=%s" % (
data['argv'],
value
))
setts[name] = value
except Exception:
logger.exception("Exception retrieving setting value: %r" % name)
return setts
# Parse command line arguments
def parse_args(self):
parser = argparse.ArgumentParser(
description=(
'Script to assist sonarr/radarr with plex imports. Will only scan the folder \n'
'that has been imported, instead of the whole library section.'
),
formatter_class=argparse.RawTextHelpFormatter
)
# Mode
parser.add_argument('cmd',
choices=('sections', 'server'),
help=(
'"sections": prints plex sections\n'
'"server": starts the application'
)
)
# Config file
parser.add_argument(self.base_settings['config']['argv'],
nargs='?',
const=None,
help='Config file location (default: %s)' % self.base_settings['config']['default']
)
# Log file
parser.add_argument(self.base_settings['logfile']['argv'],
nargs='?',
const=None,
help='Log file location (default: %s)' % self.base_settings['logfile']['default']
)
# Queue file
parser.add_argument(self.base_settings['queuefile']['argv'],
nargs='?',
const=None,
help='Queue file location (default: %s)' % self.base_settings['queuefile']['default']
)
# Logging level
parser.add_argument(self.base_settings['loglevel']['argv'],
choices=('WARN', 'INFO', 'DEBUG'),
help='Log level (default: %s)' % self.base_settings['loglevel']['default']
)
# Print help by default if no arguments
if len(sys.argv) == 1:
parser.print_help()
sys.exit(0)
else:
return vars(parser.parse_args())