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