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