-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlogic_movie.py
executable file
·496 lines (429 loc) · 22.9 KB
/
logic_movie.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# -*- coding: utf-8 -*-
#########################################################
# python
import os, sys, traceback, re, json, threading, time, shutil
from datetime import datetime
# third-party
import requests
# third-party
from flask import request, render_template, jsonify, redirect, Response, send_file
from sqlalchemy import or_, and_, func, not_, desc
import lxml.html
from lxml import etree as ET
# sjva 공용
from framework import db, scheduler, path_data, socketio, SystemModelSetting, app, py_urllib
from framework.util import Util
from framework.common.util import headers
from plugin import LogicModuleBase, default_route_socketio
from system import SystemLogicTrans
# 패키지
#from lib_metadata import SiteDaumTv, SiteTmdbTv, SiteTvingTv, SiteWavveTv
from lib_metadata import SiteNaverMovie, SiteTmdbMovie, SiteWatchaMovie, SiteUtil, SiteDaumMovie, SiteTvingMovie, SiteWavveMovie
from .plugin import P
logger = P.logger
package_name = P.package_name
ModelSetting = P.ModelSetting
from lib_metadata.server_util import MetadataServerUtil
#########################################################
class LogicMovie(LogicModuleBase):
db_default = {
'movie_db_version' : '1',
'movie_first_order' : 'daum, naver, tmdb',
'movie_use_tmdb_image' : 'False',
#'movie_use_tmdb' : 'True',
'movie_use_watcha' : 'True',
'movie_use_watcha_option' : '0',
'movie_use_watcha_collection_like_count' : '100',
'movie_total_test_search' : '',
'movie_total_test_info' : '',
'movie_naver_test_search' : '',
'movie_naver_test_info' : '',
'movie_daum_test_search' : '',
'movie_daum_test_info' : '',
'movie_tmdb_test_search' : '',
'movie_tmdb_test_info' : '',
'movie_watcha_test_search' : '',
'movie_watcha_test_info' : '',
'movie_wavve_test_search' : '',
'movie_wavve_test_info' : '',
'movie_tving_test_search' : '',
'movie_tving_test_info' : '',
'movie_wavve_mode' : '0',
'movie_use_sub_tmdb' : '1', #['모두 사용', 'Daum은 사용 안함', '사용 안함']
'movie_use_sub_tmdb_mode' : '0', #['모두 사용', 'Art만, '배우정보']
'movie_rating_score' : '70',
'movie_translate_option' : '0',
'movie_actor_trans' : 'False',
}
module_map = {'naver':SiteNaverMovie, 'daum':SiteDaumMovie, 'tmdb':SiteTmdbMovie, 'watcha':SiteWatchaMovie, 'wavve':SiteWavveMovie, 'tving':SiteTvingMovie}
module_map2 = {'N':SiteNaverMovie, 'D':SiteDaumMovie, 'T':SiteTmdbMovie, 'C':SiteWatchaMovie, 'W':SiteWavveMovie, 'V':SiteTvingMovie}
def __init__(self, P):
super(LogicMovie, self).__init__(P, 'setting')
self.name = 'movie'
def process_menu(self, sub, req):
arg = P.ModelSetting.to_dict()
arg['sub'] = self.name
try:
return render_template(f'{package_name}_{self.name}_{sub}.html', arg=arg)
except Exception as e:
logger.error(f'Exception:{str(e)}')
logger.error(traceback.format_exc())
return render_template('sample.html', title=f"{package_name}/{self.name}/{sub}")
def process_ajax(self, sub, req):
try:
ret = {}
if sub == 'test':
param = req.form['param'].strip()
call = req.form['call']
mode = req.form['mode']
tmps = param.split('|')
year = 1900
ModelSetting.set('movie_%s_test_%s' % (call, mode), param)
if len(tmps) == 2:
keyword = tmps[0].strip()
try: year = int(tmps[1].strip())
except: year = None
else:
keyword = param
if call == 'total':
if mode == 'search':
manual = (req.form['manual'] == 'manual')
ret = self.search(keyword, year=year, manual=manual)
elif mode == 'info':
ret = self.info(param)
else:
SiteClass = self.module_map[call]
if mode == 'search':
ret = SiteClass.search(keyword, year=year)
elif mode == 'info':
ret = SiteClass.info(param)
elif mode == 'search_api':
ret = SiteClass.search_api(keyword)
elif mode == 'info_api':
ret = SiteClass.info_api(param)
return jsonify(ret)
except Exception as e:
P.logger.error('Exception:%s', e)
P.logger.error(traceback.format_exc())
return jsonify({'ret':'exception', 'log':str(e)})
def process_api(self, sub, req):
if sub == 'search':
call = req.args.get('call')
manual = bool(req.args.get('manual'))
try: year = int(req.args.get('year'))
except: year = 1900
logger.debug(req.args.get('year'))
logger.debug(year)
if call == 'plex' or call == 'kodi':
return jsonify(self.search(req.args.get('keyword'), year, manual=manual))
elif sub == 'info':
call = req.args.get('call')
data = self.info(req.args.get('code'))
if call == 'kodi':
data = SiteUtil.info_to_kodi(data)
elif call == 'plex':
data['movie_rating_score'] = ModelSetting.get_int('movie_rating_score')
return jsonify(data)
elif sub == 'stream':
code = req.args.get('code')
ret = self.stream(code)
mode = req.args.get('mode')
logger.debug(ret)
logger.debug(mode)
if mode == 'redirect':
"""
if code[1] == 'W':
playurl = requests.get(ret['wavve_url'].replace('action=dash', 'action=hls')).json()['playurl'].replace('chunklist5000.m3u8', '5000/chunklist.m3u8')
return redirect(tmp)
file_content = requests.get(playurl).content
prefix = playurl.split('chunklist.m3u8')[0]
filedata = file_content.replace('0/media', prefix + '0/media')
filename = '%s.m3u8' % str(time.time())
filepath = os.path.join(path_data, 'tmp', filename)
from tool_base import ToolBaseFile
ToolBaseFile.write(filedata, filepath)
tmp = '{ddns}/file/data/tmp/{filename}?apikey={apikey}'.format(ddns=SystemModelSetting.get('ddns'), filename=filename, apikey=SystemModelSetting.get('auth_apikey'))
return redirect(tmp)
"""
if 'hls' in ret:
return redirect(ret['hls'])
else:
return jsonify(ret)
#########################################################
def search(self, keyword, year, manual=False):
try:
if isinstance(year, str):
year = int(str)
except: pass
if keyword.startswith('M'):
data = self.info(keyword)
if data is not None:
item = {}
item['code'] = keyword
item['score'] = 100
item['title'] = data['title']
item['year'] = data['year']
item['image_url'] = data['art'][0]['value']
item['desc'] = data['plot']
item['site'] = data['site']
return [item]
ret = []
site_list = ModelSetting.get_list('movie_first_order', ',')
#site_list = ['naver']
# 한글 영문 분리
split_index = -1
is_include_kor = False
for index, c in enumerate(keyword):
if ord(u'가') <= ord(c) <= ord(u'힣'):
is_include_kor = True
split_index = -1
elif ord('a') <= ord(c.lower()) <= ord('z'):
is_include_eng = True
if split_index == -1:
split_index = index
elif ord('0') <= ord(c.lower()) <= ord('9') or ord(' '):
pass
else:
split_index = -1
if is_include_kor and split_index != -1:
kor = keyword[:split_index].strip()
eng = keyword[split_index:].strip()
else:
kor = None
eng = None
for key in [keyword, kor, eng]:
logger.debug('search key : [%s] [%s]', key, year)
if key is None:
continue
for idx, site in enumerate(site_list):
if year is None:
year = 1900
else:
try: year = int(year)
except: year = 1900
site_data = self.module_map[site].search(key, year=year)
if site_data['ret'] == 'success':
for item in site_data['data']:
item['score'] -= idx
#logger.debug(item)
ret += site_data['data']
if manual:
continue
else:
if len(site_data['data']) and site_data['data'][0]['score'] > 85:
break
ret = sorted(ret, key=lambda k: k['score'], reverse=True)
if len(ret) > 0 and ret[0]['score'] > 85:
break
ret = sorted(ret, key=lambda k: k['score'], reverse=True)
for item in ret:
if item['score'] < 10:
item['score'] = 10
return ret
def info(self, code):
try:
info = None
SiteClass = self.module_map2[code[1]]
tmp = SiteClass.info(code)
if tmp['ret'] == 'success':
info = tmp['data']
if info['title'] == '':
logger.error('title empty.. change meta site....')
return
#'movie_use_sub_tmdb' : '0' #['모두 사용', 'Daum은 사용 안함', '사용 안함']
movie_use_sub_tmdb = ModelSetting.get('movie_use_sub_tmdb')
#logger.warning(movie_use_sub_tmdb)
if code[1] != 'T' and (movie_use_sub_tmdb == '0' or (movie_use_sub_tmdb == '1' and code[1] != 'D')):
try:
tmdb_info = None
for i in range(2):
tmdb_search = None
if i == 0:
tmdb_search = SiteTmdbMovie.search(info['title'], year=info['year'])
#logger.debug(json.dumps(tmdb_search, indent=4))
if tmdb_search['ret'] == 'empty':
continue
elif i == 1:
if 'title_en' in info['extra_info']:
tmdb_search = SiteTmdbMovie.search(info['extra_info']['title_en'], year=info['year'])
#logger.debug(json.dumps(tmdb_search, indent=4))
elif info['originaltitle'] != '':
tmdb_search = SiteTmdbMovie.search(info['originaltitle'], year=info['year'])
#logger.debug(json.dumps(tmdb_search, indent=4))
if tmdb_search is None:
continue
if tmdb_search['ret'] == 'success' and len(tmdb_search['data']) > 0:
logger.debug(tmdb_search['data'][0]['title'])
#logger.debug()
count = 0
for item in tmdb_search['data']:
if item['score'] == 100:
count += 1
else:
break
if count == 1:
tmdb_data = SiteTmdbMovie.info(tmdb_search['data'][0]['code'])
if tmdb_data['ret'] == 'success':
tmdb_info = tmdb_data['data']
if count == 0:
if tmdb_search['data'][0]['score'] > 85 or ('title_en' in info['extra_info'] and SiteUtil.compare(info['extra_info']['title_en'], tmdb_search['data'][0]['originaltitle'])):
tmdb_data = SiteTmdbMovie.info(tmdb_search['data'][0]['code'])
if tmdb_data['ret'] == 'success':
tmdb_info = tmdb_data['data']
if tmdb_info is not None:
break
if tmdb_info is not None:
logger.debug('tmdb :%s %s', tmdb_info['title'], tmdb_info['year'])
#logger.debug(json.dumps(tmdb_info, indent=4))
logger.debug('tmdb_info : %s', tmdb_info['title'])
movie_use_sub_tmdb_mode = ModelSetting.get('movie_use_sub_tmdb_mode')
if movie_use_sub_tmdb_mode == '0':
info['extras'] += tmdb_info['extras']
self.change_tmdb_actor_info(tmdb_info['actor'], info['actor'])
info['actor'] = tmdb_info['actor']
info['art'] += tmdb_info['art']
elif movie_use_sub_tmdb_mode == '1':
info['art'] += tmdb_info['art']
elif movie_use_sub_tmdb_mode == '2':
self.change_tmdb_actor_info(tmdb_info['actor'], info['actor'])
info['actor'] = tmdb_info['actor']
info['code_list'] += tmdb_info['code_list']
if info['plot'] == '':
info['plot'] = tmdb_info['plot']
except Exception as e:
logger.error('Exception:%s', e)
logger.error(traceback.format_exc())
logger.error('tmdb search fail..')
if True:
try:
wavve_info = None
wavve_search = SiteWavveMovie.search(info['title'], year=info['year'])
if wavve_search['ret'] == 'success' and len(wavve_search['data']) > 0:
tmp = SiteWavveMovie.info(wavve_search['data'][0]['code'])['data']
#logger.debug(json.dumps(tmp, indent=4))
if SiteUtil.compare(info['title'], tmp['title']) and abs(info['year'] - tmp['year']) <= 1:
wavve_info = tmp
if wavve_info is not None:
info['code_list'] += wavve_info['code_list']
info['art'] += wavve_info['art']
if 'wavve_stream' in wavve_info['extra_info']:
info['extra_info']['wavve_stream'] = wavve_info['extra_info']['wavve_stream']
info['extra_info']['wavve_stream']['mode'] = ModelSetting.get('movie_wavve_mode')
except Exception as e:
logger.error('Exception:%s', e)
logger.error(traceback.format_exc())
logger.error('wavve search fail..')
if True:
try:
tving_info = None
tving_search = SiteTvingMovie.search(info['title'], year=info['year'])
if tving_search['ret'] == 'success' and len(tving_search['data']) > 0:
tmp = SiteTvingMovie.info(tving_search['data'][0]['code'])
#logger.debug(json.dumps(tmp, indent=4))
if tmp['ret'] == 'success':
tmp = tmp['data']
if SiteUtil.compare(info['title'], tmp['title']) and abs(info['year'] - tmp['year']) <= 1:
tving_info = tmp
if tving_info is not None:
info['code_list'] += tving_info['code_list']
info['art'] += tving_info['art']
if 'tving_stream' in tving_info['extra_info']:
info['extra_info']['tving_stream'] = tving_info['extra_info']['tving_stream']
except Exception as e:
logger.error('Exception:%s', e)
logger.error(traceback.format_exc())
logger.error('tving search fail..')
if ModelSetting.get_bool('movie_use_watcha'):
try:
movie_use_watcha_option = ModelSetting.get('movie_use_watcha_option')
watcha_info = None
watcha_search = SiteWatchaMovie.search(info['title'], year=info['year'])
if watcha_search['ret'] == 'success' and len(watcha_search['data'])>0:
if watcha_search['data'][0]['score'] > 85:
watcha_data = SiteWatchaMovie.info(watcha_search['data'][0]['code'], like_count=ModelSetting.get_int('movie_use_watcha_collection_like_count'))
if watcha_data['ret'] == 'success':
watcha_info = watcha_data['data']
if watcha_info is not None:
if movie_use_watcha_option in ['0', '1']:
info['review'] = watcha_info['review']
info['code_list'] += watcha_info['code_list']
info['code_list'].append(['google_search', u'영화 ' + info['title']])
for idx, review in enumerate(info['review']):
if idx >= len(info['code_list']):
break
if info['code_list'][idx][0] == 'naver_id':
review['source'] = u'네이버'
review['link'] = 'https://movie.naver.com/movie/bi/mi/basic.nhn?code=%s' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'daum_id':
review['source'] = u'다음'
review['link'] = 'https://movie.daum.net/moviedb/main?movieId=%s' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'wavve_id':
review['source'] = u'웨이브'
review['link'] = 'https://www.wavve.com/player/movie?movieid=%s' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'tving_id':
review['source'] = u'티빙'
review['link'] = 'https://www.tving.com/movie/player/%s' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'tmdb_id':
review['source'] = u'TMDB'
review['link'] = 'https://www.themoviedb.org/movie/%s?language=ko' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'imdb_id':
review['source'] = u'IMDB'
review['link'] = 'https://www.imdb.com/title/%s/' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'watcha_id':
review['source'] = u'왓챠 피디아'
review['link'] = 'https://pedia.watcha.com/ko-KR/contents/%s' % info['code_list'][idx][1]
elif info['code_list'][idx][0] == 'google_search':
review['source'] = u'구글 검색'
review['link'] = 'https://www.google.com/search?q=%s' % info['code_list'][idx][1]
if movie_use_watcha_option in ['0', '2']:
info['tag'] += watcha_info['tag']
except Exception as e:
logger.error('Exception:%s', e)
logger.error(traceback.format_exc())
logger.error('watcha search fail..')
self.process_trans(info)
return info
except Exception as e:
P.logger.error('Exception:%s', e)
P.logger.error(traceback.format_exc())
def process_trans(self, data):
mode = ModelSetting.get('movie_translate_option')
if mode == '0':
return
else:
function = SystemLogicTrans.get_trans_func(mode)
if SiteUtil.is_include_hangul(data['plot']) == False:
data['plot'] = function(data['plot'], source='en')
if ModelSetting.get_bool('movie_actor_trans'):
for actor in data['actor']:
if SiteUtil.is_include_hangul(actor['name']) == False:
actor['name'] = function(actor['name'], source='en')
if SiteUtil.is_include_hangul(actor['role']) == False:
actor['role'] = function(actor['role'], source='en')
return data
def change_tmdb_actor_info(self, tmdb_info, portal_info):
if len(portal_info) == 0:
return
for tmdb in tmdb_info:
#logger.debug(tmdb['name'])
for portal in portal_info:
#logger.debug(portal['originalname'])
if tmdb['name'] == portal['originalname']:
tmdb['name'] = portal['name']
tmdb['role'] = portal['role']
break
def stream(self, code):
try:
logger.debug('code : %s', code)
if code[1] == 'V':
from support.site.tving import SupportTving
data = SupportTving.ins.get_info(code[2:], 'stream50')
#logger.debug(data)
return data['play_info']
elif code[1] == 'W':
import framework.wavve.api as Wavve
data = {'wavve_url':Wavve.streaming2('movie', code[2:], 'FHD', return_url=True)}
return data
except Exception as e:
P.logger.error('Exception:%s', e)
P.logger.error(traceback.format_exc())