trackma 0.6__py3.5.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. EGG-INFO/PKG-INFO +19 -0
  2. EGG-INFO/SOURCES.txt +37 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/entry_points.txt +8 -0
  5. EGG-INFO/not-zip-safe +1 -0
  6. EGG-INFO/requires.txt +10 -0
  7. EGG-INFO/top_level.txt +1 -0
  8. trackma/__init__.py +0 -0
  9. trackma/__pycache__/__init__.cpython-35.pyc +0 -0
  10. trackma/__pycache__/accounts.cpython-35.pyc +0 -0
  11. trackma/__pycache__/data.cpython-35.pyc +0 -0
  12. trackma/__pycache__/engine.cpython-35.pyc +0 -0
  13. trackma/__pycache__/messenger.cpython-35.pyc +0 -0
  14. trackma/__pycache__/tracker.cpython-35.pyc +0 -0
  15. trackma/__pycache__/utils.cpython-35.pyc +0 -0
  16. trackma/accounts.py +145 -0
  17. trackma/data/anilist.jpg +0 -0
  18. trackma/data/hb.jpg +0 -0
  19. trackma/data/icon.png +0 -0
  20. trackma/data/mal.jpg +0 -0
  21. trackma/data/melative.jpg +0 -0
  22. trackma/data/shikimori.jpg +0 -0
  23. trackma/data/vndb.jpg +0 -0
  24. trackma/data.py +597 -0
  25. trackma/engine.py +818 -0
  26. trackma/extras/AnimeInfoExtractor.py +308 -0
  27. trackma/extras/__init__.py +1 -0
  28. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-35.pyc +0 -0
  29. trackma/extras/__pycache__/__init__.cpython-35.pyc +0 -0
  30. trackma/extras/__pycache__/plex.cpython-35.pyc +0 -0
  31. trackma/extras/plex.py +101 -0
  32. trackma/lib/__init__.py +0 -0
  33. trackma/lib/__pycache__/__init__.cpython-35.pyc +0 -0
  34. trackma/lib/__pycache__/lib.cpython-35.pyc +0 -0
  35. trackma/lib/__pycache__/libanilist.cpython-35.pyc +0 -0
  36. trackma/lib/__pycache__/libhb.cpython-35.pyc +0 -0
  37. trackma/lib/__pycache__/libmal.cpython-35.pyc +0 -0
  38. trackma/lib/__pycache__/libmelative.cpython-35.pyc +0 -0
  39. trackma/lib/__pycache__/libshikimori.cpython-35.pyc +0 -0
  40. trackma/lib/__pycache__/libvndb.cpython-35.pyc +0 -0
  41. trackma/lib/lib.py +162 -0
  42. trackma/lib/libanilist.py +406 -0
  43. trackma/lib/libhb.py +237 -0
  44. trackma/lib/libmal.py +707 -0
  45. trackma/lib/libmelative.py +204 -0
  46. trackma/lib/libshikimori.py +340 -0
  47. trackma/lib/libvndb.py +375 -0
  48. trackma/messenger.py +42 -0
  49. trackma/tracker.py +390 -0
  50. trackma/ui/__init__.py +0 -0
  51. trackma/ui/__pycache__/__init__.cpython-35.pyc +0 -0
  52. trackma/ui/__pycache__/cli.cpython-35.pyc +0 -0
  53. trackma/ui/__pycache__/curses.cpython-35.pyc +0 -0
  54. trackma/ui/__pycache__/gtkui.cpython-35.pyc +0 -0
  55. trackma/ui/__pycache__/qtui.cpython-35.pyc +0 -0
  56. trackma/ui/cli.py +835 -0
  57. trackma/ui/curses.py +1061 -0
  58. trackma/ui/gtkui.py +2647 -0
  59. trackma/ui/qtui.py +3046 -0
  60. trackma/utils.py +379 -0
trackma/ui/cli.py ADDED
@@ -0,0 +1,835 @@
1
+ # This file is part of Trackma.
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
15
+ #
16
+
17
+ import sys
18
+ try:
19
+ import readline
20
+ except ImportError:
21
+ pass # readline is optional
22
+ import cmd
23
+ import shlex
24
+ import textwrap
25
+ import re
26
+ from operator import itemgetter # Used for sorting list
27
+
28
+ from trackma.engine import Engine
29
+ from trackma.accounts import AccountManager
30
+ from trackma import messenger
31
+ from trackma import utils
32
+
33
+ _DEBUG = False
34
+ _COLOR_RESET = '\033[0m'
35
+ _COLOR_ENGINE = '\033[0;32m'
36
+ _COLOR_DATA = '\033[0;33m'
37
+ _COLOR_API = '\033[0;34m'
38
+ _COLOR_TRACKER = '\033[0;35m'
39
+ _COLOR_ERROR = '\033[0;31m'
40
+ _COLOR_FATAL = '\033[1;31m'
41
+
42
+ _COLOR_AIRING = '\033[0;34m'
43
+
44
+ # We must use mark these with special characters for
45
+ # readline to calculate line width correctly
46
+ _PCOLOR_RESET = '\001\033[0m\002'
47
+ _PCOLOR_USER = '\001\033[0;32m\002'
48
+ _PCOLOR_API = '\001\033[0;34m\002'
49
+ _PCOLOR_MEDIATYPE = '\001\033[0;33m\002'
50
+ _PCOLOR_FILTER = '\001\033[0;35m\002'
51
+
52
+
53
+ class Trackma_cmd(cmd.Cmd):
54
+ """
55
+ Main program, inherits from the useful Cmd class
56
+ for interactive console
57
+ """
58
+ engine = None
59
+ filter_num = 1
60
+ sort = 'title'
61
+ completekey = 'Tab'
62
+ cmdqueue = []
63
+ stdout = sys.stdout
64
+ sortedlist = []
65
+ needed_args = {
66
+ 'filter': (0, 1),
67
+ 'sort': 1,
68
+ 'mediatype': (0, 1),
69
+ 'info': 1,
70
+ 'search': 1,
71
+ 'add': 1,
72
+ 'delete': 1,
73
+ 'play': (1, 2),
74
+ 'update': 2,
75
+ 'score': 2,
76
+ 'status': 2,
77
+ }
78
+
79
+ def __init__(self):
80
+ print('Trackma v'+utils.VERSION+' Copyright (C) 2012 z411')
81
+ print('This program comes with ABSOLUTELY NO WARRANTY; for details type `info\'')
82
+ print('This is free software, and you are welcome to redistribute it')
83
+ print('under certain conditions; see the file COPYING for details.')
84
+ print()
85
+
86
+ self.accountman = Trackma_accounts()
87
+ self.account = self.accountman.select_account(False)
88
+
89
+ def _update_prompt(self):
90
+ self.prompt = "{c_u}{u}{c_r} [{c_a}{a}{c_r}] ({c_mt}{mt}{c_r}) {c_s}{s}{c_r} >> ".format(
91
+ u = self.engine.get_userconfig('username'),
92
+ a = self.engine.api_info['shortname'],
93
+ mt = self.engine.api_info['mediatype'],
94
+ s = self.engine.mediainfo['statuses_dict'][self.filter_num].lower().replace(' ', ''),
95
+ c_r = _PCOLOR_RESET,
96
+ c_u = _PCOLOR_USER,
97
+ c_a = _PCOLOR_API,
98
+ c_mt = _PCOLOR_MEDIATYPE,
99
+ c_s = _COLOR_RESET
100
+ )
101
+
102
+ def _load_list(self, *args):
103
+ showlist = self.engine.filter_list(self.filter_num)
104
+ sortedlist = sorted(showlist, key=itemgetter(self.sort))
105
+ self.sortedlist = list(enumerate(sortedlist, 1))
106
+
107
+ def _get_show(self, title):
108
+ # Attempt parsing list index
109
+ # otherwise use title
110
+ try:
111
+ index = int(title)-1
112
+ return self.sortedlist[index]
113
+ except (ValueError, AttributeError, IndexError):
114
+ return self.engine.get_show_info_title(title)
115
+
116
+ def _ask_update(self, show, episode):
117
+ do_update = input("Should I update %s to episode %d? [y/N] " % (show['title'], episode))
118
+ if do_update.lower() == 'y':
119
+ self.engine.set_episode(show['id'], episode)
120
+
121
+ def start(self):
122
+ """
123
+ Initializes the engine
124
+
125
+ Creates an Engine object and starts it.
126
+ """
127
+ print('Initializing engine...')
128
+ self.engine = Engine(self.account, self.messagehandler)
129
+ self.engine.connect_signal('show_added', self._load_list)
130
+ self.engine.connect_signal('show_deleted', self._load_list)
131
+ self.engine.connect_signal('status_changed', self._load_list)
132
+ self.engine.connect_signal('episode_changed', self._load_list)
133
+ self.engine.connect_signal('prompt_for_update', self._ask_update)
134
+ self.engine.start()
135
+
136
+ # Start with default filter selected
137
+ self.filter_num = self.engine.mediainfo['statuses'][0]
138
+ self._load_list()
139
+ self._update_prompt()
140
+
141
+ print()
142
+ print("Ready. Type 'help' for a list of commands.")
143
+ print("Press tab for autocompletion and up/down for command history.")
144
+ self.do_filter(None) # Show available filters
145
+ print()
146
+
147
+ def do_help(self, arg):
148
+ if arg:
149
+ try:
150
+ doc = getattr(self, 'do_' + arg).__doc__
151
+ if doc:
152
+ (name, args, expl, usage) = self._parse_doc(arg, doc)
153
+
154
+ print()
155
+ print(name)
156
+ for line in expl:
157
+ print(" {}".format(line))
158
+ if args:
159
+ print("\n Arguments:")
160
+ for arg in args:
161
+ if arg[2]:
162
+ print(" {}: {}".format(arg[0], arg[1]))
163
+ else:
164
+ print(" {} (optional): {}".format(arg[0], arg[1]))
165
+ if usage:
166
+ print("\n Usage: " + usage)
167
+ print()
168
+ return
169
+ except AttributeError:
170
+ pass
171
+
172
+ print("No help available.")
173
+ return
174
+ else:
175
+ CMD_LENGTH = 11
176
+ ARG_LENGTH = 13
177
+
178
+ (height, width) = utils.get_terminal_size()
179
+ prev_width = CMD_LENGTH + ARG_LENGTH + 3
180
+
181
+ tw = textwrap.TextWrapper()
182
+ tw.width = width - 2
183
+ tw.subsequent_indent = ' ' * prev_width
184
+
185
+ print()
186
+ print(" {0:>{1}} {2:{3}} {4}".format(
187
+ 'command', CMD_LENGTH,
188
+ 'args', ARG_LENGTH,
189
+ 'description'))
190
+ print(" " + "-"*(min(prev_width+81, width-3)))
191
+
192
+ names = self.get_names()
193
+ names.sort()
194
+ cmds = []
195
+ for name in names:
196
+ if name[:3] == 'do_':
197
+ doc = getattr(self, name).__doc__
198
+ if not doc:
199
+ continue
200
+
201
+ cmd = name[3:]
202
+ (name, args, expl, usage) = self._parse_doc(cmd, doc)
203
+
204
+ line = " {0:>{1}} {2:{3}} {4}".format(
205
+ name, CMD_LENGTH,
206
+ '<' + ','.join( a[0] for a in args) + '>', ARG_LENGTH,
207
+ expl[0])
208
+ print(tw.fill(line))
209
+
210
+ print()
211
+ print("Use `help <command>` for detailed information.")
212
+ print()
213
+
214
+
215
+ def do_account(self, args):
216
+ """
217
+ Switch to a different account.
218
+ """
219
+
220
+ self.account = self.accountman.select_account(True)
221
+ self.engine.reload(account=self.account)
222
+
223
+ # Start with default filter selected
224
+ self.filter_num = self.engine.mediainfo['statuses'][0]
225
+ self._load_list()
226
+ self._update_prompt()
227
+
228
+ def do_filter(self, args):
229
+ """
230
+ Changes the filtering of list by status.s
231
+
232
+ :optparam status Name of status to filter
233
+ :usage filter [filter type]
234
+ """
235
+ # Query the engine for the available statuses
236
+ # that the user can choose
237
+ if args:
238
+ try:
239
+ self.filter_num = self._guess_status(args[0].lower())
240
+ self._load_list()
241
+ self._update_prompt()
242
+ except KeyError:
243
+ print("Invalid filter.")
244
+ else:
245
+ print("Available statuses: %s" % ', '.join( v.lower().replace(' ', '') for v in self.engine.mediainfo['statuses_dict'].values() ))
246
+
247
+ def do_sort(self, args):
248
+ """
249
+ Change of the lists
250
+
251
+ :param type Sort type; available types: id, title, my_progress, total, my_score
252
+ :usage sort <sort type>
253
+ """
254
+ sorts = ('id', 'title', 'my_progress', 'total', 'my_score')
255
+ if args[0] in sorts:
256
+ self.sort = args[0]
257
+ self._load_list()
258
+ else:
259
+ print("Invalid sort.")
260
+
261
+ def do_mediatype(self, args):
262
+ """
263
+ Reloads engine with different mediatype.
264
+ Call with no arguments to see supported mediatypes.
265
+
266
+ :optparam mediatype Mediatype name
267
+ :usage mediatype [mediatype]
268
+ """
269
+ if args:
270
+ if args[0] in self.engine.api_info['supported_mediatypes']:
271
+ self.engine.reload(mediatype=args[0])
272
+
273
+ # Start with default filter selected
274
+ self.filter_num = self.engine.mediainfo['statuses'][0]
275
+ self._load_list()
276
+ self._update_prompt()
277
+ else:
278
+ print("Invalid mediatype.")
279
+ else:
280
+ print("Supported mediatypes: %s" % ', '.join(self.engine.api_info['supported_mediatypes']))
281
+
282
+ def do_ls(self,args):
283
+ self.do_list(args)
284
+
285
+ def do_list(self, args):
286
+ """
287
+ Lists all shows available in the local list.
288
+
289
+ :name list|ls
290
+ """
291
+ # Show the list in memory
292
+ self._make_list(self.sortedlist)
293
+
294
+ def do_info(self, args):
295
+ """
296
+ Gets detailed information about a local show.
297
+
298
+ :param show Show index or title.
299
+ :usage info <show index or title>
300
+ """
301
+ try:
302
+ show = self._get_show(args[0])
303
+ details = self.engine.get_show_details(show)
304
+ except utils.TrackmaError as e:
305
+ self.display_error(e)
306
+ return
307
+
308
+ print("Title: %s" % details['title'])
309
+ for line in details['extra']:
310
+ print("%s: %s" % line)
311
+
312
+ def do_search(self, args):
313
+ """
314
+ Does a regex search on shows in the local lists.
315
+
316
+ :param pattern Regex pattern to search for.
317
+ :usage search <pattern>
318
+ """
319
+ sortedlist = list(v for v in self.sortedlist if re.match(args[0], v[1]['title'], re.I))
320
+ self._make_list(sortedlist)
321
+
322
+ def do_add(self, args):
323
+ """
324
+ Search for a show in the remote service and add it.
325
+
326
+ :param pattern Show criteria to search.
327
+ :usage add <pattern>
328
+ """
329
+ try:
330
+ entries = self.engine.search(args[0])
331
+ except utils.TrackmaError as e:
332
+ self.display_error(e)
333
+ return
334
+
335
+ for i, entry in enumerate(entries, start=1):
336
+ print("%d: (%s) %s" % (i, entry['type'], entry['title']))
337
+ do_update = input("Choose show to add (blank to cancel): ")
338
+ if do_update != '':
339
+ try:
340
+ show = entries[int(do_update)-1]
341
+ except ValueError:
342
+ print("Choice must be numeric.")
343
+ return
344
+ except IndexError:
345
+ print("Invalid show.")
346
+ return
347
+
348
+ # Tell the engine to add the show
349
+ try:
350
+ self.engine.add_show(show, self.filter_num)
351
+ except utils.TrackmaError as e:
352
+ self.display_error(e)
353
+
354
+ def do_delete(self, args):
355
+ """
356
+ Deletes a show from the local list.
357
+
358
+ :param show Show index or title.
359
+ :usage delete <show index or title>
360
+ """
361
+ try:
362
+ show = self._get_show(args[0])
363
+
364
+ do_delete = input("Delete %s? [y/N] " % show['title'])
365
+ if do_delete.lower() == 'y':
366
+ self.engine.delete_show(show)
367
+ except utils.TrackmaError as e:
368
+ self.display_error(e)
369
+
370
+ def do_scaneps(self, args):
371
+ """
372
+ Re-scans the local library.
373
+ """
374
+ self.engine.scan_library()
375
+
376
+ def do_random(self, args):
377
+ """
378
+ Starts the media player with a random new episode.
379
+ """
380
+ try:
381
+ self.engine.play_random()
382
+ except utils.TrackmaError as e:
383
+ self.display_error(e)
384
+
385
+ def do_play(self, args):
386
+ """
387
+ Starts the media player with the specified episode number (next if not specified).
388
+
389
+ :param show Episode index or title.
390
+ :optparam ep Episode number. Assume next if not specified.
391
+ :usage play <show index or title> [episode number]
392
+ """
393
+ try:
394
+ episode = 0
395
+ show = self._get_show(args[0])
396
+
397
+ # If the user specified an episode, play it
398
+ # otherwise play the next episode not watched yet
399
+ try:
400
+ episode = args[1]
401
+ if episode == (show['my_progress'] + 1):
402
+ playing_next = True
403
+ else:
404
+ playing_next = False
405
+ except IndexError:
406
+ playing_next = True
407
+
408
+ played_episode = self.engine.play_episode(show, episode)
409
+ except utils.TrackmaError as e:
410
+ self.display_error(e)
411
+
412
+ def do_update(self, args):
413
+ """
414
+ Updates the progress of a show to the specified episode.
415
+
416
+ :param show Show index or name.
417
+ :param ep Episode number (numeric).
418
+ :usage update <show index or name> <episode number>
419
+ """
420
+ try:
421
+ show = self._get_show(args[0])
422
+ self.engine.set_episode(show['id'], args[1])
423
+ except IndexError:
424
+ print("Missing arguments.")
425
+ except utils.TrackmaError as e:
426
+ self.display_error(e)
427
+
428
+ def do_score(self, args):
429
+ """
430
+ Changes the score of a show.
431
+
432
+ :param show Show index or name.
433
+ :param score Score to set (numeric/decimal).
434
+ :usage score <show index or name> <score>
435
+ """
436
+ try:
437
+ show = self._get_show(args[0])
438
+ self.engine.set_score(show['id'], args[1])
439
+ except IndexError:
440
+ print("Missing arguments.")
441
+ except utils.TrackmaError as e:
442
+ self.display_error(e)
443
+
444
+ def do_status(self, args):
445
+ """
446
+ Changes the status of a show.
447
+ Use the command `filter` without arguments to see the available statuses.
448
+
449
+ :param show Show index or name.
450
+ :param status Status name. Use `filter` without args to list them.
451
+ :usage status <show index or name> <status name>
452
+ """
453
+ try:
454
+ _showtitle = args[0]
455
+ _filter = args[1]
456
+ except IndexError:
457
+ print("Missing arguments.")
458
+ return
459
+
460
+ try:
461
+ _filter_num = self._guess_status(_filter)
462
+ except KeyError:
463
+ print("Invalid filter.")
464
+ return
465
+
466
+ try:
467
+ show = self._get_show(_showtitle)
468
+ self.engine.set_status(show['id'], _filter_num)
469
+ except utils.TrackmaError as e:
470
+ self.display_error(e)
471
+
472
+ def do_send(self, args):
473
+ """
474
+ Sends queued changes to the remote service.
475
+ """
476
+ try:
477
+ self.engine.list_upload()
478
+ except utils.TrackmaError as e:
479
+ self.display_error(e)
480
+
481
+ def do_retrieve(self, args):
482
+ """
483
+ Retrieves the remote list overwrites the local one.
484
+ """
485
+ try:
486
+ if self.engine.get_queue():
487
+ answer = input("There are unqueued changes. Overwrite local list? [y/N] ")
488
+ if answer.lower() == 'y':
489
+ self.engine.list_download()
490
+ else:
491
+ self.engine.list_download()
492
+ self._load_list()
493
+ except utils.TrackmaError as e:
494
+ self.display_error(e)
495
+
496
+ def do_undoall(self, args):
497
+ """
498
+ Undo all changes in queue.
499
+ """
500
+ try:
501
+ self.engine.undoall()
502
+ except utils.TrackmaError as e:
503
+ self.display_error(e)
504
+
505
+ def do_viewqueue(self, args):
506
+ """
507
+ List the queued changes.
508
+ """
509
+ queue = self.engine.get_queue()
510
+ if len(queue):
511
+ print("Queue:")
512
+ for show in queue:
513
+ print("- %s" % show['title'])
514
+ else:
515
+ print("Queue is empty.")
516
+
517
+ def do_exit(self, args):
518
+ self.do_quit(args)
519
+
520
+ def do_quit(self, args):
521
+ """
522
+ Quits the program.
523
+
524
+ :name quit|exit
525
+ """
526
+ try:
527
+ self.engine.unload()
528
+ except utils.TrackmaError as e:
529
+ self.display_error(e)
530
+
531
+ print('Bye!')
532
+ sys.exit(0)
533
+
534
+ def do_EOF(self, args):
535
+ print()
536
+ self.do_quit(args)
537
+
538
+ def complete_update(self, text, line, begidx, endidx):
539
+ if text:
540
+ return self.engine.regex_list_titles(text)
541
+
542
+ def complete_play(self, text, line, begidx, endidx):
543
+ if text:
544
+ return self.engine.regex_list_titles(text)
545
+
546
+ def complete_score(self, text, line, begidx, endidx):
547
+ if text:
548
+ return self.engine.regex_list_titles(text)
549
+
550
+ def complete_status(self, text, line, begidx, endidx):
551
+ if text:
552
+ return self.engine.regex_list_titles(text)
553
+
554
+ def complete_delete(self, text, line, begidx, endidx):
555
+ if text:
556
+ return self.engine.regex_list_titles(text)
557
+
558
+ def complete_filter(self, text, line, begidx, endidx):
559
+ return [v.lower().replace(' ', '') for v in self.engine.mediainfo['statuses_dict'].values()]
560
+
561
+ def parse_args(self, arg):
562
+ if arg:
563
+ return shlex.split(arg)
564
+ else:
565
+ return []
566
+
567
+ def emptyline(self):
568
+ return
569
+
570
+ def onecmd(self, line):
571
+ """ Override. """
572
+ cmd, arg, line = self.parseline(line)
573
+ if not line:
574
+ return self.emptyline()
575
+ if cmd is None:
576
+ return self.default(line)
577
+ self.lastcmd = line
578
+ if line == 'EOF' :
579
+ self.lastcmd = ''
580
+ if cmd == '':
581
+ return self.default(line)
582
+ elif cmd == 'help':
583
+ return self.do_help(arg)
584
+ else:
585
+ return self.execute(cmd, arg, line)
586
+
587
+ def execute(self, cmd, arg, line):
588
+ try:
589
+ func = getattr(self, 'do_' + cmd)
590
+ except AttributeError:
591
+ return self.default(line)
592
+
593
+ args = self.parse_args(arg)
594
+
595
+ try:
596
+ needed = self.needed_args[cmd]
597
+ except KeyError:
598
+ needed = 0
599
+
600
+ if isinstance(needed, int):
601
+ needed = (needed, needed)
602
+
603
+ if needed[0] <= len(args) <= needed[1]:
604
+ return func(args)
605
+ else:
606
+ print("Incorrent number of arguments. See `help %s`" % cmd)
607
+
608
+ def display_error(self, e):
609
+ print("%s%s: %s%s" % (_COLOR_ERROR, type(e), e, _COLOR_RESET))
610
+
611
+ def messagehandler(self, classname, msgtype, msg):
612
+ """
613
+ Handles and shows messages coming from
614
+ the engine messenger to provide feedback.
615
+ """
616
+ color_escape = ''
617
+ color_reset = _COLOR_RESET
618
+
619
+ if classname == 'Engine':
620
+ color_escape = _COLOR_ENGINE
621
+ elif classname == 'Data':
622
+ color_escape = _COLOR_DATA
623
+ elif classname == 'Tracker':
624
+ color_escape = _COLOR_TRACKER
625
+ elif classname.startswith('lib'):
626
+ color_escape = _COLOR_API
627
+ else:
628
+ color_reset = ''
629
+
630
+ if msgtype == messenger.TYPE_INFO:
631
+ print("%s%s: %s%s" % (color_escape, classname, msg, color_reset))
632
+ elif msgtype == messenger.TYPE_WARN:
633
+ print("%s%s warning: %s%s" % (color_escape, classname, msg, color_reset))
634
+ elif _DEBUG and msgtype == messenger.TYPE_DEBUG:
635
+ print("%s%s: %s%s" % (color_escape, classname, msg, color_reset))
636
+
637
+ def _guess_status(self, string):
638
+ for k, v in self.engine.mediainfo['statuses_dict'].items():
639
+ if string.lower() == v.lower().replace(' ', ''):
640
+ return k
641
+ raise KeyError
642
+
643
+ def _parse_doc(self, cmd, doc):
644
+ lines = doc.split('\n')
645
+ name = cmd
646
+ args = []
647
+ expl = []
648
+ usage = None
649
+
650
+ for line in lines:
651
+ line = line.strip()
652
+ if line[:6] == ":param":
653
+ args.append( line[7:].split(' ', 1) + [True] )
654
+ elif line[:9] == ":optparam":
655
+ args.append( line[10:].split(' ', 1) + [False] )
656
+ elif line[:6] == ':usage':
657
+ usage = line[7:]
658
+ elif line[:5] == ':name':
659
+ name = line[6:]
660
+ elif line:
661
+ expl.append(line)
662
+
663
+ return (name, args, expl, usage)
664
+
665
+ def _make_list(self, showlist):
666
+ """
667
+ Helper function for printing a formatted show list
668
+ """
669
+ # Fixed column widths
670
+ col_id_length = 7
671
+ col_index_length = 6
672
+ col_title_length = 5
673
+ col_episodes_length = 9
674
+ col_score_length = 6
675
+
676
+ # Calculate maximum width for the title column
677
+ # based on the width of the terminal
678
+ (height, width) = utils.get_terminal_size()
679
+ max_title_length = width - col_id_length - col_episodes_length - col_score_length - col_index_length - 5
680
+
681
+ # Find the widest title so we can adjust the title column
682
+ for index, show in showlist:
683
+ if len(show['title']) > col_title_length:
684
+ if len(show['title']) > max_title_length:
685
+ # Stop if we exceeded the maximum column width
686
+ col_title_length = max_title_length
687
+ break
688
+ else:
689
+ col_title_length = len(show['title'])
690
+
691
+ # Print header
692
+ print("| {0:{1}} {2:{3}} {4:{5}} {6:{7}} |".format(
693
+ 'Index', col_index_length,
694
+ 'Title', col_title_length,
695
+ 'Progress', col_episodes_length,
696
+ 'Score', col_score_length))
697
+
698
+ # List shows
699
+ for index, show in showlist:
700
+ if self.engine.mediainfo['has_progress']:
701
+ episodes_str = "{0:3} / {1}".format(show['my_progress'], show['total'])
702
+ else:
703
+ episodes_str = "-"
704
+
705
+ # Truncate title if needed
706
+ title_str = show['title']
707
+ title_str = title_str[:max_title_length] if len(title_str) > max_title_length else title_str
708
+
709
+ # Color title according to status
710
+ if show['status'] == utils.STATUS_AIRING:
711
+ colored_title = _COLOR_AIRING + title_str + _COLOR_RESET
712
+ else:
713
+ colored_title = title_str
714
+
715
+ print("| {0:^{1}} {2}{3} {4:{5}} {6:^{7}} |".format(
716
+ index, col_index_length,
717
+ colored_title,
718
+ '.' * (col_title_length-len(show['title'])),
719
+ episodes_str, col_episodes_length,
720
+ show['my_score'], col_score_length))
721
+
722
+ # Print result count
723
+ print('%d results' % len(showlist))
724
+ print()
725
+
726
+ class Trackma_accounts(AccountManager):
727
+ def _get_id(self, index):
728
+ if index < 1:
729
+ raise IndexError
730
+
731
+ return self.indexes[index-1]
732
+
733
+ def select_account(self, bypass):
734
+ if not bypass and self.get_default():
735
+ return self.get_default()
736
+ if self.get_default():
737
+ self.set_default(None)
738
+
739
+ while True:
740
+ print('--- Accounts ---')
741
+ self.list_accounts()
742
+ key = input("Input account number ([r#]emember, [a]dd, [c]ancel, [d]elete, [q]uit): ")
743
+
744
+ if key.lower() == 'a':
745
+ available_libs = ', '.join(sorted(utils.available_libs.keys()))
746
+
747
+ print("--- Add account ---")
748
+ import getpass
749
+ api = input('Enter API (%s): ' % available_libs)
750
+ try:
751
+ selected_api = utils.available_libs[api]
752
+ except KeyError:
753
+ print("Invalid API.")
754
+ continue
755
+
756
+ if selected_api[2] == utils.LOGIN_PASSWD:
757
+ username = input('Enter username: ')
758
+ password = getpass.getpass('Enter password (no echo): ')
759
+ elif selected_api[2] == utils.LOGIN_OAUTH:
760
+ username = input('Enter account name: ')
761
+ print('OAuth Authentication')
762
+ print('--------------------')
763
+ print('This website requires OAuth authentication.')
764
+ print('Please go to the following URL with your browser,')
765
+ print('follow the steps and paste the given PIN code here.')
766
+ print()
767
+ print(selected_api[3])
768
+ print()
769
+ password = input('PIN: ')
770
+
771
+ try:
772
+ self.add_account(username, password, api)
773
+ print('Done.')
774
+ except utils.AccountError as e:
775
+ print('Error: %s' % e)
776
+ elif key.lower() == 'd':
777
+ print("--- Delete account ---")
778
+ num = input('Account number to delete: ')
779
+ try:
780
+ num = int(num)
781
+ account_id = self._get_id(num)
782
+ confirm = input("Are you sure you want to delete account %d (%s)? [y/N] " % (num, self.get_account(account_id)['username']))
783
+ if confirm.lower() == 'y':
784
+ self.delete_account(account_id)
785
+ print('Account %d deleted.' % num)
786
+ except ValueError:
787
+ print("Invalid value.")
788
+ except IndexError:
789
+ print("Account doesn't exist.")
790
+ elif key.lower() == 'q':
791
+ sys.exit(0)
792
+ else:
793
+ try:
794
+ if key[0] == 'r':
795
+ key = key[1:]
796
+ remember = True
797
+ else:
798
+ remember = False
799
+
800
+ num = int(key)
801
+ account_id = self._get_id(num)
802
+ if remember:
803
+ self.set_default(account_id)
804
+
805
+ return self.get_account(account_id)
806
+ except ValueError:
807
+ print("Invalid value.")
808
+ except IndexError:
809
+ print("Account doesn't exist.")
810
+
811
+ def list_accounts(self):
812
+ accounts = self.get_accounts()
813
+ self.indexes = []
814
+
815
+ print("Available accounts:")
816
+ i = 0
817
+ if accounts:
818
+ for k, account in accounts:
819
+ print("%i: %s (%s)" % (i+1, account['username'], account['api']))
820
+ self.indexes.append(k)
821
+ i += 1
822
+ else:
823
+ print("No accounts.")
824
+
825
+
826
+ def main():
827
+ main_cmd = Trackma_cmd()
828
+ try:
829
+ main_cmd.start()
830
+ main_cmd.cmdloop()
831
+ except utils.TrackmaFatal as e:
832
+ print("%s%s: %s%s" % (_COLOR_FATAL, type(e), e, _COLOR_RESET))
833
+
834
+ if __name__ == '__main__':
835
+ main()