-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
·270 lines (225 loc) · 9.68 KB
/
app.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
#!/usr/bin/python3
from flask import Flask, render_template, request, redirect, url_for, session, jsonify
from plexsync.plexsync import PlexSync
import json
import urllib.parse
import logging
import traceback
import sys
app = Flask(__name__)
app.config['SECRET_KEY'] = 'changeme'
app.config['LOGGER_NAME'] = 'plexsync'
def as_json():
# If content type is application/json, return json, else render the template
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > \
request.accept_mimetypes['text/html']
plexsync = None
@app.route('/')
def index():
if not request.script_root:
# this assumes that the 'index' view function handles the path '/'
request.script_root = url_for('index', _external=True)
return render_template('index.html')
@app.route('/#', methods=['POST'])
def login():
session['username'] = request.form['username']
session['password'] = request.form['password']
try:
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
return redirect(url_for('home', _scheme='https', _external=True), code=303)
except Exception as e:
return json.dumps(str(e))
@app.route('/home', methods=['GET'])
def home():
try:
plexsync = PlexSync()
plexAccount = plexsync.getAccount(username=session['username'], password=session['password'])
servers = plexsync.getServers(plexAccount)
sortedServers = sorted([server.name for server in servers])
return render_template('home.html', server_list=sortedServers)
except KeyError:
return redirect('/')
@app.route('/servers/<string:serverName>', methods=['GET','POST'])
def sections(serverName):
print(f"routing for {serverName}")
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
server = plexsync.getServer(serverName)
sections = plexsync.getSections(server)
sortedSections = sorted([section.title for section in sections])
return json.dumps(sortedSections, ensure_ascii=False)
@app.route('/servers/<string:serverName>/<string:section>', methods=['GET','POST'])
def media(serverName, section):
print(f"routing for {serverName} - {section}")
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
server = plexsync.getServer(serverName)
results = plexsync.getResults(server, section)
sortedResults = sorted([r.title for r in results])
return json.dumps(sortedResults, ensure_ascii=False)
@app.route('/search', methods=['POST'])
def search():
guid = request.form['guid']
guid = urllib.parse.unquote(guid)
server = request.form['server']
section = request.form['section']
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
theirServer = plexsync.getServer(server)
section = theirServer.library.sectionByID(section)
result = section.search(guid=guid).pop()
m = plexsync.getAPIObject(result)
response = plexsync.sendMediaToThirdParty(m)
return render_template('third_party.html', message=response)
@app.route('/download', methods=['POST'])
def download():
guid = request.form['guid']
guid = urllib.parse.unquote(guid)
server = request.form['server']
section = request.form['section']
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
theirServer = plexsync.getServer(server)
section = theirServer.library.sectionByID(section)
result = section.search(guid=guid).pop()
result.download()
@app.route('/transfer', methods=['POST'])
def transfer():
try:
server = request.form['server']
section = request.form['section']
guid = request.form['guid']
guid = urllib.parse.unquote(guid)
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
ownedServers = plexsync.getOwnedServers()
currentUserServer = session['yourServer']
app.logger.debug(f"ownedServers {ownedServers}")
app.logger.debug(f"currentServer {currentUserServer}")
authorized = False
for s in ownedServers:
if s.friendlyName == currentUserServer:
app.logger.debug(f"authorized")
authorized = True
theirServer = plexsync.getServer(server)
section = theirServer.library.sectionByID(section)
result = section.search(guid=guid).pop()
if authorized:
app.logger.debug("building task")
try:
task_result = plexsync.transfer.delay(theirServer.friendlyName, guid)
except Exception as e:
app.logger.error(f"Exception {e}")
return json.dumps(e)
msg = f"Transferring {result.title} to {currentUserServer}"
response = {'key' : result.ratingKey, 'title': result.title, 'task': task_result.id }
return jsonify(result=response, message=msg)
else:
app.logger.debug(f"not authorized")
msg = f"Not authorized to transfer {result.title} to {currentUserServer}"
return json.dumps(msg)
except Exception as e:
return json.dumps(str(e))
@app.route('/compare/<string:yourServerName>/<string:theirServerName>', methods=['GET'])
@app.route('/compare/<string:yourServerName>/<string:theirServerName>/<string:sectionName>', methods=['GET'])
def compare(yourServerName, theirServerName, sectionName=None):
try:
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
sectionsToCompare = []
if not sectionName:
settings = plexsync.getSettings()
sectionsToCompare = settings.get('sections', 'sections').split(",")
else:
sectionsToCompare.append(sectionName)
yourServer = plexsync.getServer(yourServerName)
session['yourServer'] = yourServerName
theirServer = plexsync.getServer(theirServerName)
for section in sectionsToCompare:
yourLibrary = plexsync.getResults(yourServer, section)
theirLibrary = plexsync.getResults(theirServer, section)
results = plexsync.compareLibrariesAsResults(yourLibrary, theirLibrary)
app.logger.debug(f"{section} {len(yourLibrary)} in yours {len(theirLibrary)} in theirs")
app.logger.debug(f"{len(results)} your diff")
result_list = []
for r in results:
m = plexsync.getAPIObject(r)
result_dict = {}
result_dict['title'] = m.title
result_dict['downloadURL'] = m.downloadURL
result_dict['overview'] = m.overview
result_dict['sectionID'] = m.librarySectionID
result_dict['year'] = m.year
result_dict['guid'] = urllib.parse.quote_plus(m.guid)
result_dict['server'] = theirServer.friendlyName
if m.image and len(m.image) > 0:
result_dict['image'] = m.image
result_dict['rating'] = m.rating
result_list.append(result_dict)
except Exception as e:
app.logger.exception(e)
response = jsonify(str(e))
response.status_code = 500
return response
if as_json():
return jsonify(result_list)
else:
return render_template('media.html', media=result_list)
@app.route('/compareResults/<string:yourServerName>/<string:theirServerName>/<string:sectionName>', methods=['GET'])
def compareResults(yourServerName, theirServerName, sectionName=None):
plexsync = PlexSync()
plexsync.getAccount(session['username'], session['password'])
sectionsToCompare = []
if not sectionName:
settings = plexsync.getSettings()
sectionsToCompare = settings.get('sections', 'sections').split(",")
else:
sectionsToCompare.append(sectionName)
yourServer = plexsync.getServer(yourServerName)
theirServer = plexsync.getServer(theirServerName)
for section in sectionsToCompare:
yourLibrary = plexsync.getResults(yourServer, section)
theirLibrary = plexsync.getResults(theirServer, section)
results = plexsync.compareLibrariesAsResults(yourLibrary, theirLibrary)
print(f"{section} {len(yourLibrary)} in yours {len(theirLibrary)} in theirs")
print(f"{len(results)} your diff")
return json.dumps([r.title for r in results], ensure_ascii=False)
@app.route('/task/<task_id>')
def taskstatus(task_id):
plexsync = PlexSync(taskOnly=True)
task = plexsync.getTask(task_id)
if task.state == 'PENDING':
# job did not start yet
response = {
'state': task.state,
'current': 0,
'total': 1,
'status': 'Pending...'
}
elif task.state != 'FAILURE':
response = {
'state': task.state,
'current': task.info.get('current', 0),
'total': task.info.get('total', 1),
'status': task.info.get('status', '')
}
if 'result' in task.info:
response['result'] = task.info['result']
else:
# something went wrong in the background job
response = {
'state': task.state,
'current': 1,
'total': 1,
'status': str(task.info), # this is the exception raised
}
return jsonify(response)
if __name__ == '__main__':
#https://stackoverflow.com/questions/26423984/unable-to-connect-to-flask-app-on-docker-from-host
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.DEBUG)
app.run(host='0.0.0.0', port=5000)