forked from dersphere/XBMC-CouchPotato-Manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addon.py
615 lines (567 loc) · 22 KB
/
addon.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Tristan Fischer ([email protected])
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import xbmcaddon
import os
from xbmcswift2 import Plugin, xbmc, xbmcgui
from resources.lib.api import \
CouchPotatoApi, AuthenticationError, ConnectionError
REMOTE_DBG = False
# append pydev remote debugger
if REMOTE_DBG:
# Make pydev debugger works for auto reload.
# Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
try:
import pysrc.pydevd as pydevd
# stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
pydevd.settrace('localhost', stdoutToServer=True, stderrToServer=True)
except ImportError:
sys.stderr.write("Error: " +
"You must add org.python.pydev.debug.pysrc to your PYTHONPATH.")
sys.exit(1)
STRINGS = {
# Root menu
'all_movies': 30000,
'add_new_wanted': 30001,
'wanted_movies': 30002,
'done_movies': 30003,
'status_list': 30004,
# Context menu
'addon_settings': 30100,
'refresh_releases': 30101,
'delete_movie': 30102,
'delete_release': 30103,
'download_release': 30104,
'ignore_release': 30105,
'youtube_trailer': 30106,
'full_refresh': 30107,
# Dialogs
'enter_movie_title': 30110,
'select_movie': 30111,
'select_profile': 30112,
'delete_movie_head': 30113,
'delete_movie_l1': 30114,
'select_default_profile': 30115,
# Error dialogs
'connection_error': 30120,
'wrong_credentials': 30121,
'wrong_network': 30122,
'want_set_now': 30123,
# Noticications
'wanted_added': 30130,
'no_movie_found': 30131,
'success': 30132,
# Help Dialog
'release_help_head': 30140,
'release_help_l1': 30141,
'release_help_l2': 30142,
'release_help_l3': 30143,
# Labels in Plot:
'type': 30150,
'provider': 30151,
'provider_extra': 30152,
'age': 30153,
'seed_leech': 30154,
'size_mb': 30155,
'description': 30156,
}
YT_TRAILER_URL = (
'plugin://plugin.video.youtube/'
'?path=/root/search&feed=search&search=%s+Trailer'
)
plugin = Plugin()
addon = xbmcaddon.Addon()
wantedpath = addon.getSetting('wanted_path')
@plugin.cached()
def get_status_list():
return api.get_status_list()
@plugin.route('/')
def show_root_menu():
def context_menu():
return [
(
_('addon_settings'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='open_settings'
)
),
]
def context_menu_wanted():
return [
(
_('full_refresh'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='do_full_refresh'
)
),
]
items = [
{'label': _('add_new_wanted'),
'replace_context_menu': True,
'context_menu': context_menu(),
'path': plugin.url_for(endpoint='add_new_wanted')},
{'label': _('all_movies'),
'replace_context_menu': True,
'context_menu': context_menu(),
'path': plugin.url_for(endpoint='show_all_movies')},
{'label': _('wanted_movies'),
'replace_context_menu': True,
'context_menu': context_menu_wanted(),
'path': plugin.url_for(endpoint='show_movies', status='active')},
{'label': _('done_movies'),
'replace_context_menu': True,
'context_menu': context_menu(),
'path': plugin.url_for(endpoint='show_movies', status='done')},
# {'label': _('status_list'),
# 'replace_context_menu': True,
# 'context_menu': context_menu(),
# 'path': plugin.url_for(endpoint='show_status_list')},
]
return plugin.finish(items)
@plugin.route('/status_list/')
def show_status_list():
def context_menu():
return [
(
_('addon_settings'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='open_settings'
)
),
]
items = []
for status in get_status_list():
items.append({
'label': status['label'],
'replace_context_menu': True,
'context_menu': context_menu(),
'path': plugin.url_for(
endpoint='show_movies',
status=status['identifier']
)
})
return plugin.finish(items)
@plugin.route('/movies/', name='show_all_movies', options={'status': None})
@plugin.route('/movies/status/<status>/')
def show_movies(status):
def context_menu(movie_id, movie_title):
return [
(
_('refresh_releases'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='refresh_releases',
library_id=movie_id
)
),
(
_('delete_movie'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='delete_movie',
library_id=movie_id
)
),
(
_('youtube_trailer'),
'XBMC.Container.Update(%s)' % YT_TRAILER_URL % movie_title
),
(
_('addon_settings'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='open_settings'
)
),
]
def get_status(status_id):
return [s for s in status_list if s['id'] == status_id]
releases = plugin.get_storage('releases')
releases.clear()
status_list = get_status_list()
items = []
plugin.set_content('movies')
if not status:
movies = api.get_movies()
else:
movies = api.get_movies(status=status)
i = 0
for i, movie in enumerate(movies):
info = movie['library']['info']
movie_id = str(movie['library_id'])
label = info['titles'][0]
status_label = get_status(movie['status_id'])[0]['label']
label = u'[%s] %s' % (status_label, label)
releases[movie_id] = movie['releases']
items.append({
'label': label,
'thumbnail': (info['images']['poster'] or [''])[0],
'info': {
'count': i,
'originaltitle': info.get('original_title', ''),
'writer': ', '.join(info.get('writers', [])),
'director': ', '.join(info.get('directors', [])),
'code': info.get('imdb', ''),
'year': info.get('year', 0),
'plot': info.get('plot', ''),
'genre': ', '.join(info.get('genres', [])),
'tagline': info.get('tagline', ''),
'actors': info.get('actors', []), # broken in XBMC Frodo
'rating': info.get('rating', {}).get('imdb', [0, 0])[0],
'votes': info.get('rating', {}).get('imdb', [0, 0])[1]
},
'replace_context_menu': True,
'context_menu': context_menu(movie_id, info['titles'][0]),
'properties': {
'fanart_image': (info['images'].get('backdrop') or [''])[0],
},
'path': plugin.url_for(
endpoint='show_releases',
library_id=movie_id
),
})
releases.sync()
sort_methods = ['playlist_order', 'video_rating', 'video_year']
return plugin.finish(items, sort_methods=sort_methods)
@plugin.route('/movies/add/')
def add_new_wanted():
if 'imdb_id' in plugin.request.args:
imdb_id = plugin.request.args['imdb_id'][0]
movielist=movie_list()
for movie in movielist:
if movie['identifiers']['imdb']==imdb_id:
if movie['status']=='active':
try:
profil=movie['profile_id']
profiles = api.get_profiles()
for profile in profiles:
if profile['_id']==profil:
profilemovie=profile['label']
stringnot=movie['title']+u' est déjà dans votre wanted list en '+profilemovie
except:
stringnot=movie['title']+u' est déjà dans votre wanted list'
else:
try:
if movie['releases'][0]['is_3d']:
quality=u'3D'
else:
quality=movie['releases'][0]['quality']
stringnot=movie['title']+u' est déjà dans votre bibliothèque en '+quality
except:
stringnot=movie['title']+u' est déjà dans votre bibliothèque'
xbmcgui.Dialog().notification(u'Déja dans CouchPotato', u'Le film '+stringnot, xbmcgui.NOTIFICATION_INFO, 5000)
return
imdb_id = plugin.request.args['imdb_id'][0]
search_title = plugin.request.args['title'][0]
if imdb_id:
return add_new_wanted_by_id(imdb_id,search_title)
if 'title' in plugin.request.args:
search_title = plugin.request.args['title'][0]
else:
search_title = plugin.keyboard(heading=_('enter_movie_title'))
if search_title:
movies = api.search_wanted(search_title)
if not movies:
if not wantedpath:
xbmcgui.Dialog().notification(u'Répertoire manquant pour wanted list', u'Vous devez spécifiez un répertoire dans les options', xbmcgui.NOTIFICATION_INFO, 5000)
else:
alreadywanted=[]
if os.path.isfile(wantedpath+'\WANTEDMOVIE.txt'):
LF=open(wantedpath+'\WANTEDMOVIE.txt', 'r')
for line in LF:
alreadywanted.append(line.replace('\n',''))
LF.close()
if search_title in alreadywanted:
xbmcgui.Dialog().notification('Déjà présent dans fichier wanted', search_title+' est déjà présent dans votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
else:
LF = open(wantedpath+'\WANTEDMOVIE.txt', 'a')
strtowrite=search_title
LF.write(strtowrite+'\n')
LF.close()
xbmcgui.Dialog().notification('Film ajouté dans fichier wanted', search_title+' ajouté dans votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
return
items = [
'%s %s' % (movie['titles'][0],
('(%s)' % movie['year']) if movie.get('year', False) else '')
for movie in movies
]
selected = xbmcgui.Dialog().select(
_('select_movie'), items
)
if selected >= 0:
selected_movie = movies[selected]
movielist=movie_list()
for movie in movielist:
if movie['title'] in selected_movie['titles']:
if movie['status']=='active':
try:
profil=movie['profile_id']
profiles = api.get_profiles()
for profile in profiles:
if profile['_id']==profil:
profilemovie=profile['label']
stringnot=movie['title']+u' est déjà dans votre wanted list en '+profilemovie
except:
stringnot=movie['title']+u' est déjà dans votre wanted list'
else:
try:
if movie['releases'][0]['is_3d']:
quality=u'3D'
else:
quality=movie['releases'][0]['quality']
stringnot=movie['title']+u' est déjà dans votre bibliothèque en '+quality
except:
stringnot=movie['title']+u' est déjà dans votre bibliothèque'
xbmcgui.Dialog().notification(u'Déja dans CouhchPotato', u'Le film '+stringnot, xbmcgui.NOTIFICATION_INFO, 5000)
return
profile_id = ask_profile()
if profile_id:
success = api.add_wanted(
profile_id=profile_id,
movie_identifier=selected_movie['imdb']
)
if success:
xbmcgui.Dialog().notification(u'Ajouté dans CouchPotato', u'Le film '+search_title+u' a été ajouté à votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
else:
xbmcgui.Dialog().notification(u'Problème', u"Un problème est sruvenu lors de l'ajout de "+search_title+'. Consultez la log de CouchPotato', xbmcgui.NOTIFICATION_INFO, 5000)
elif selected < 0:
if not wantedpath:
xbmcgui.Dialog().notification(u'Répertoire manquant pour wanted list', u'Vous devez spécifiez un répertoire dans les options', xbmcgui.NOTIFICATION_INFO, 5000)
else:
alreadywanted=[]
if os.path.isfile(wantedpath+'\WANTEDMOVIE.txt'):
LF=open(wantedpath+'\WANTEDMOVIE.txt', 'r')
for line in LF:
alreadywanted.append(line.replace('\n',''))
LF.close()
if search_title in alreadywanted:
xbmcgui.Dialog().notification('Déjà présent dans fichier wanted', search_title+' est déjà présent dans votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
else:
LF = open(wantedpath+'\WANTEDMOVIE.txt', 'a')
strtowrite=search_title
LF.write(strtowrite+'\n')
LF.close()
xbmcgui.Dialog().notification('Film ajouté dans fichier wanted', search_title+' ajouté dans votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
return
@plugin.route('/movies/add-by-id/<imdb_id>')
def add_new_wanted_by_id(imdb_id,title):
profile_id = ask_profile()
if profile_id:
success = api.add_wanted(
profile_id=profile_id,
movie_identifier=imdb_id
)
if success:
xbmcgui.Dialog().notification(u'Ajouté dans CouchPotato', u'Le film '+title.decode("utf-8")+u' a été ajouté à votre wanted list', xbmcgui.NOTIFICATION_INFO, 5000)
else:
xbmcgui.Dialog().notification(u'Problème', u"Un problème est sruvenu lors de l'ajout de "+title+'. Consultez la log de CouchPotato', xbmcgui.NOTIFICATION_INFO, 5000)
def ask_profile():
if not plugin.get_setting('default_profile', str):
askthreed = xbmcgui.Dialog().yesno(u"3D", u"Télécharger en 3D ?")
profiles = api.get_profiles()
for profile in profiles:
if profile['label']=='Best':
profileBest=profile
elif profile['label']=='3D HD':
profileThreed=profile
if askthreed:
selected_profile=profileThreed
else:
selected_profile=profileBest
confirm = xbmcgui.Dialog().yesno(u"Confirmation", u"Confirmez-vous ?")
if confirm:
profile_id = selected_profile['_id']
else:
return
else:
profile_id = plugin.get_setting('default_profile', int)
return profile_id
def movie_list():
movielist=api.get_movies()
return movielist
@plugin.route('/movies/<library_id>/releases/')
def show_releases(library_id):
def context_menu(release_id):
return [
(
_('delete_release'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='delete_release',
release_id=release_id
)
),
(
_('download_release'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='download_release',
release_id=release_id
)
),
(
_('ignore_release'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='ignore_release',
release_id=release_id
)
),
(
_('addon_settings'),
'XBMC.RunPlugin(%s)' % plugin.url_for(
endpoint='open_settings'
)
),
]
def labelize(string_id, content):
return u'[B]%s[/B]: %s' % (_(string_id), content)
releases = plugin.get_storage('releases')
items = []
for release in releases[library_id]:
info = release['info']
t = info['type'][0].upper()
items.append({
'label': '[%s %d] %s' % (t, info['score'], info['name']),
'info': {
'size': info['provider'] * 1024,
'plot': '[CR]'.join((
labelize('type', info['type']),
labelize('provider', info['provider']),
labelize('provider_extra', info['provider_extra']),
labelize('age', info['age']),
labelize('seed_leech', '%s/%s' % (
info.get('seeders', '0'), info.get('leechers', '0'))
),
labelize('size_mb', info['size']),
labelize('description', info['description'])
)),
},
'replace_context_menu': True,
'context_menu': context_menu(release['id']),
'path': plugin.url_for(
endpoint='show_release_help',
foo=release['id'] # to have items with different URLs
),
})
return plugin.finish(items)
@plugin.route('/movies/all/refresh')
def do_full_refresh():
success = api.do_full_refresh()
if success:
plugin.notify(msg=_('success'))
@plugin.route('/movies/<library_id>/refresh')
def refresh_releases(library_id):
success = api.refresh_releases(library_id)
if success:
plugin.notify(msg=_('success'))
@plugin.route('/movies/<library_id>/delete')
def delete_movie(library_id):
confirmed = xbmcgui.Dialog().yesno(
_('delete_movie_head'),
_('delete_movie_l1')
)
if confirmed:
success = api.delete_movie(library_id)
if success:
plugin.notify(msg=_('success'))
@plugin.route('/release/<release_id>/delete')
def delete_release(release_id):
success = api.delete_release(release_id)
if success:
plugin.notify(msg=_('success'))
@plugin.route('/release/<release_id>/download')
def download_release(release_id):
success = api.download_release(release_id)
if success:
plugin.notify(msg=_('success'))
@plugin.route('/release/<release_id>/ignore')
def ignore_release(release_id):
success = api.ignore_release(release_id)
if success:
plugin.notify(msg=_('success'))
@plugin.route('/release/help')
def show_release_help():
xbmcgui.Dialog().ok(
_('release_help_head'),
_('release_help_l1'),
_('release_help_l2'),
_('release_help_l3'),
)
@plugin.route('/settings/default_profile')
def set_default_profile():
profiles = api.get_profiles()
items = [profile['label'] for profile in profiles]
selected = xbmcgui.Dialog().select(
_('select_default_profile'), items
)
if selected >= 0:
selected_profile = profiles[selected]
plugin.set_setting('default_profile', str(selected_profile['_id']))
elif selected == -1:
plugin.set_setting('default_profile', '')
@plugin.route('/settings')
def open_settings():
plugin.open_settings()
def get_api():
logged_in = False
while not logged_in:
cp_api = CouchPotatoApi()
try:
new_api_key = cp_api.connect(
hostname=plugin.get_setting('hostname', unicode),
port=plugin.get_setting('port', int),
use_https=plugin.get_setting('use_https', bool),
username=plugin.get_setting('username', unicode),
password=plugin.get_setting('password', unicode),
api_key=plugin.get_setting('api_key', str),
url_base=plugin.get_setting('url_base', str),
ba_username=plugin.get_setting('ba_username', unicode),
ba_password=plugin.get_setting('ba_password', unicode),
)
except AuthenticationError:
try_again = xbmcgui.Dialog().yesno(
_('connection_error'),
_('wrong_credentials'),
_('want_set_now')
)
if not try_again:
return
plugin.open_settings()
continue
except ConnectionError:
try_again = xbmcgui.Dialog().yesno(
_('connection_error'),
_('wrong_network'),
_('want_set_now')
)
if not try_again:
return
plugin.open_settings()
continue
else:
logged_in = True
if plugin.get_setting('api_key', str) != new_api_key:
plugin.set_setting('api_key', new_api_key)
return cp_api
def log(text):
plugin.log.info(text)
def _(string_id):
if string_id in STRINGS:
return plugin.get_string(STRINGS[string_id]).encode('utf-8')
else:
log('String is missing: %s' % string_id)
return string_id
if __name__ == '__main__':
api = get_api()
if api:
plugin.run()