forked from DobyTang/LazyLibrarian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LazyLibrarian.py
executable file
·291 lines (247 loc) · 11.8 KB
/
LazyLibrarian.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
from __future__ import print_function
import locale
import os
import platform
import sys
import threading
import time
import shutil
import lazylibrarian
from lazylibrarian import webStart, logger, versioncheck, dbupgrade
from lazylibrarian.formatter import check_int
# noinspection PyUnresolvedReferences
from lib.six.moves import configparser
# The following should probably be made configurable at the settings level
# This fix is put in place for systems with broken SSL (like QNAP)
opt_out_of_certificate_verification = True
if opt_out_of_certificate_verification:
# noinspection PyBroadException
try:
import ssl
# noinspection PyProtectedMember
ssl._create_default_https_context = ssl._create_unverified_context
except Exception:
pass
# ==== end block (should be configurable at settings level)
def main():
# rename this thread
threading.currentThread().name = "MAIN"
# Set paths
if hasattr(sys, 'frozen'):
lazylibrarian.FULL_PATH = os.path.abspath(sys.executable)
else:
lazylibrarian.FULL_PATH = os.path.abspath(__file__)
lazylibrarian.PROG_DIR = os.path.dirname(lazylibrarian.FULL_PATH)
lazylibrarian.ARGS = sys.argv[1:]
lazylibrarian.SYS_ENCODING = None
try:
locale.setlocale(locale.LC_ALL, "")
lazylibrarian.SYS_ENCODING = locale.getpreferredencoding()
except (locale.Error, IOError):
pass
# for OSes that are poorly configured I'll just force UTF-8
# windows cp1252 can't handle some accented author names,
# eg "Marie Kondō" U+014D: LATIN SMALL LETTER O WITH MACRON, but utf-8 does
if not lazylibrarian.SYS_ENCODING or lazylibrarian.SYS_ENCODING in (
'ANSI_X3.4-1968', 'US-ASCII', 'ASCII') or '1252' in lazylibrarian.SYS_ENCODING:
lazylibrarian.SYS_ENCODING = 'UTF-8'
# Set arguments
from optparse import OptionParser
p = OptionParser()
p.add_option('-d', '--daemon', action="store_true",
dest='daemon', help="Run the server as a daemon")
p.add_option('-q', '--quiet', action="store_true",
dest='quiet', help="Don't log to console")
p.add_option('--debug', action="store_true",
dest='debug', help="Show debuglog messages")
p.add_option('--nolaunch', action="store_true",
dest='nolaunch', help="Don't start browser")
p.add_option('--update', action="store_true",
dest='update', help="Update to latest version (only git or source installs)")
p.add_option('--port',
dest='port', default=None,
help="Force webinterface to listen on this port")
p.add_option('--datadir',
dest='datadir', default=None,
help="Path to the data directory")
p.add_option('--config',
dest='config', default=None,
help="Path to config.ini file")
p.add_option('-p', '--pidfile',
dest='pidfile', default=None,
help="Store the process id in the given file")
p.add_option('--loglevel',
dest='loglevel', default=None,
help="Debug loglevel")
options, args = p.parse_args()
lazylibrarian.LOGLEVEL = 1
if options.debug:
lazylibrarian.LOGLEVEL = 2
if options.quiet:
lazylibrarian.LOGLEVEL = 0
if options.daemon:
if 'windows' not in platform.system().lower():
lazylibrarian.DAEMON = True
# lazylibrarian.daemonize()
else:
print("Daemonize not supported under Windows, starting normally")
if options.nolaunch:
lazylibrarian.CONFIG['LAUNCH_BROWSER'] = False
if options.update:
lazylibrarian.SIGNAL = 'update'
# This is the "emergency recovery" update in case lazylibrarian won't start.
# Set up some dummy values for the update as we have not read the config file yet
lazylibrarian.CONFIG['GIT_PROGRAM'] = ''
lazylibrarian.CONFIG['GIT_USER'] = 'lazylibrarian'
lazylibrarian.CONFIG['GIT_REPO'] = 'lazylibrarian'
lazylibrarian.CONFIG['LOGLIMIT'] = 2000
versioncheck.getInstallType()
if lazylibrarian.CONFIG['INSTALL_TYPE'] not in ['git', 'source']:
lazylibrarian.SIGNAL = None
print('Cannot update, not a git or source installation')
else:
lazylibrarian.shutdown(restart=True, update=True)
if options.loglevel:
try:
lazylibrarian.LOGLEVEL = int(options.loglevel)
except:
pass
if options.datadir:
lazylibrarian.DATADIR = str(options.datadir)
else:
lazylibrarian.DATADIR = lazylibrarian.PROG_DIR
if options.config:
lazylibrarian.CONFIGFILE = str(options.config)
else:
lazylibrarian.CONFIGFILE = os.path.join(lazylibrarian.DATADIR, "config.ini")
if options.pidfile:
if lazylibrarian.DAEMON:
lazylibrarian.PIDFILE = str(options.pidfile)
# create and check (optional) paths
if not os.path.isdir(lazylibrarian.DATADIR):
try:
os.makedirs(lazylibrarian.DATADIR)
except OSError:
raise SystemExit('Could not create data directory: ' + lazylibrarian.DATADIR + '. Exit ...')
if not os.access(lazylibrarian.DATADIR, os.W_OK):
raise SystemExit('Cannot write to the data directory: ' + lazylibrarian.DATADIR + '. Exit ...')
print("Lazylibrarian is starting up...")
time.sleep(4) # allow a bit of time for old task to exit if restarting. Needs to free logfile and server port.
# create database and config
lazylibrarian.DBFILE = os.path.join(lazylibrarian.DATADIR, 'lazylibrarian.db')
lazylibrarian.CFG = configparser.RawConfigParser()
lazylibrarian.CFG.read(lazylibrarian.CONFIGFILE)
# REMINDER ############ NO LOGGING BEFORE HERE ###############
# There is no point putting in any logging above this line, as its not set till after initialize.
lazylibrarian.initialize()
if lazylibrarian.CONFIG['VERSIONCHECK_INTERVAL'] == 0:
logger.debug('Automatic update checks are disabled')
# pretend we're up to date so we don't keep warning the user
# version check button will still override this if you want to
lazylibrarian.CONFIG['LATEST_VERSION'] = lazylibrarian.CONFIG['CURRENT_VERSION']
lazylibrarian.CONFIG['COMMITS_BEHIND'] = 0
else:
# Set the install type (win,git,source) &
# check the version when the application starts
versioncheck.checkForUpdates()
logger.debug('Current Version [%s] - Latest remote version [%s] - Install type [%s]' % (
lazylibrarian.CONFIG['CURRENT_VERSION'], lazylibrarian.CONFIG['LATEST_VERSION'],
lazylibrarian.CONFIG['INSTALL_TYPE']))
if check_int(lazylibrarian.CONFIG['GIT_UPDATED'], 0) == 0:
if lazylibrarian.CONFIG['CURRENT_VERSION'] == lazylibrarian.CONFIG['LATEST_VERSION']:
if lazylibrarian.CONFIG['INSTALL_TYPE'] == 'git' and lazylibrarian.CONFIG['COMMITS_BEHIND'] == 0:
lazylibrarian.CONFIG['GIT_UPDATED'] = str(int(time.time()))
logger.debug('Setting update timestamp to now')
# flatpak insists on PROG_DIR being read-only so we have to move version.txt into CACHEDIR
old_file = os.path.join(lazylibrarian.PROG_DIR, 'version.txt')
version_file = os.path.join(lazylibrarian.CACHEDIR, 'version.txt')
if os.path.isfile(old_file):
if not os.path.isfile(version_file):
try:
with open(old_file, 'r') as s:
with open(version_file, 'w') as d:
d.write(s.read())
except OSError:
logger.warn("Unable to copy version.txt")
try:
os.remove(old_file)
except OSError:
pass
# for dockers that haven't updated correctly from github to gitlab, force source install
if lazylibrarian.CONFIG['CURRENT_VERSION'] != lazylibrarian.CONFIG['LATEST_VERSION']:
if lazylibrarian.CONFIG['INSTALL_TYPE'] == 'git' and lazylibrarian.CONFIG['COMMITS_BEHIND'] == 0:
if os.path.exists('/app/lazylibrarian/.git'):
os.remove(version_file)
shutil.rmtree('/app/lazylibrarian/.git')
lazylibrarian.CONFIG['INSTALL_TYPE'] = 'source'
lazylibrarian.CONFIG['GIT_USER'] = 'LazyLibrarian'
lazylibrarian.CONFIG['GIT_HOST'] = 'gitlab.com'
lazylibrarian.CONFIG['GITLAB_TOKEN'] = 'gitlab+deploy-token-26212:[email protected]'
lazylibrarian.config_write('Git')
if not os.path.isfile(version_file) and lazylibrarian.CONFIG['INSTALL_TYPE'] == 'source':
# User may be running an old source zip, so try to force update
lazylibrarian.CONFIG['COMMITS_BEHIND'] = 1
lazylibrarian.SIGNAL = 'update'
# but only once in case the update fails, don't loop
with open(version_file, 'w') as f:
f.write("UNKNOWN SOURCE")
if lazylibrarian.CONFIG['COMMITS_BEHIND'] <= 0 and lazylibrarian.SIGNAL == 'update':
lazylibrarian.SIGNAL = None
if lazylibrarian.CONFIG['COMMITS_BEHIND'] == 0:
logger.debug('Not updating, LazyLibrarian is already up to date')
else:
logger.debug('Not updating, LazyLibrarian has local changes')
if lazylibrarian.DAEMON:
lazylibrarian.daemonize()
# Try to start the server.
if options.port:
lazylibrarian.CONFIG['HTTP_PORT'] = int(options.port)
logger.info('Starting LazyLibrarian on forced port: %s, webroot "%s"' %
(lazylibrarian.CONFIG['HTTP_PORT'], lazylibrarian.CONFIG['HTTP_ROOT']))
else:
lazylibrarian.CONFIG['HTTP_PORT'] = int(lazylibrarian.CONFIG['HTTP_PORT'])
logger.info('Starting LazyLibrarian on port: %s, webroot "%s"' %
(lazylibrarian.CONFIG['HTTP_PORT'], lazylibrarian.CONFIG['HTTP_ROOT']))
webStart.initialize({
'http_port': lazylibrarian.CONFIG['HTTP_PORT'],
'http_host': lazylibrarian.CONFIG['HTTP_HOST'],
'http_root': lazylibrarian.CONFIG['HTTP_ROOT'],
'http_user': lazylibrarian.CONFIG['HTTP_USER'],
'http_pass': lazylibrarian.CONFIG['HTTP_PASS'],
'http_proxy': lazylibrarian.CONFIG['HTTP_PROXY'],
'https_enabled': lazylibrarian.CONFIG['HTTPS_ENABLED'],
'https_cert': lazylibrarian.CONFIG['HTTPS_CERT'],
'https_key': lazylibrarian.CONFIG['HTTPS_KEY'],
'opds_enabled': lazylibrarian.CONFIG['OPDS_ENABLED'],
'opds_authentication': lazylibrarian.CONFIG['OPDS_AUTHENTICATION'],
'opds_username': lazylibrarian.CONFIG['OPDS_USERNAME'],
'opds_password': lazylibrarian.CONFIG['OPDS_PASSWORD'],
})
if lazylibrarian.CONFIG['LAUNCH_BROWSER'] and not options.nolaunch:
lazylibrarian.launch_browser(lazylibrarian.CONFIG['HTTP_HOST'],
lazylibrarian.CONFIG['HTTP_PORT'],
lazylibrarian.CONFIG['HTTP_ROOT'])
curr_ver = dbupgrade.upgrade_needed()
if curr_ver:
lazylibrarian.UPDATE_MSG = 'Updating database to version %s' % curr_ver
threading.Thread(target=dbupgrade.dbupgrade, name="DB_UPGRADE", args=[curr_ver]).start()
lazylibrarian.start()
while True:
if not lazylibrarian.SIGNAL:
try:
time.sleep(1)
except KeyboardInterrupt:
lazylibrarian.shutdown()
else:
if lazylibrarian.SIGNAL == 'shutdown':
lazylibrarian.shutdown()
elif lazylibrarian.SIGNAL == 'restart':
lazylibrarian.shutdown(restart=True)
elif lazylibrarian.SIGNAL == 'update':
lazylibrarian.shutdown(restart=True, update=True)
lazylibrarian.SIGNAL = None
if __name__ == "__main__":
main()