File: gpo

package info (click to toggle)
gpodder 3.11.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,272 kB
  • sloc: python: 19,713; sh: 574; xml: 122; makefile: 112
file content (1303 lines) | stat: -rwxr-xr-x 45,771 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# gPodder - A media aggregator and podcast client
# Copyright (c) 2005-2018 The gPodder Team
#
# gPodder is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# gPodder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


# gpo - A better command-line interface to gPodder using the gPodder API
# by Thomas Perl <thp@gpodder.org>; 2009-05-07


"""
  Usage: gpo [--verbose|-v|--quiet|-q] [COMMAND] [params...]

  - Subscription management -

    subscribe URL [TITLE]      Subscribe to a new feed at URL (as TITLE)
    search QUERY               Search the gpodder.net directory for QUERY
    toplist                    Show the gpodder.net top-subscribe podcasts

    import FILENAME|URL        Subscribe to all podcasts in an OPML file
    export FILENAME            Export all subscriptions to an OPML file

    rename URL TITLE           Rename feed at URL to TITLE
    unsubscribe URL            Unsubscribe from feed at URL
    enable URL                 Enable feed updates for the feed at URL
    disable URL                Disable feed updates for the feed at URL

    info URL                   Show information about feed at URL
    list                       List all subscribed podcasts
    update [URL]               Check for new episodes (all or only at URL)

  - Episode management -

    download [URL] [GUID]      Download new episodes (all or only from URL) or single GUID
    delete [URL] [GUID]        Delete from feed at URL an episode with given GUID
    pending [URL]              List new episodes (all or only from URL)
    episodes [--guid] [URL]    List episodes with or without GUIDs (all or only from URL)
    partial [--guid]           List partially downloaded episodes with or without GUIDs
    resume [--guid]            Resume partially downloaded episodes or single GUID

  - Episode management -

    sync                       Sync podcasts to device

  - Configuration -

    set [key] [value]          List one (all) keys or set to a new value

  - Extension management -

    extensions [LIST]          List all available extensions
    extension info <NAME>      Information about an extension
    extension enable <NAME>    Enable an extension
    extension disable <NAME>   Disable an extension

  - Other commands -

    youtube URL                Resolve the YouTube URL to a download URL
    rewrite OLDURL NEWURL      Change the feed URL of [OLDURL] to [NEWURL]

"""


import collections
import contextlib
import functools
import inspect
import itertools
import logging
import os
import pydoc
import re
import shlex
import sys
import textwrap
import threading

try:
    import readline
except ImportError:
    readline = None

try:
    import fcntl
    import struct
    import termios
except ImportError:
    fcntl = None
    struct = None
    termios = None

# A poor man's argparse/getopt - but it works for our use case :)
verbose = False
for flag in ('-v', '--verbose'):
    if flag in sys.argv:
        sys.argv.remove(flag)
        verbose = True
        break
quiet = False
for flag in ('-q', '--quiet'):
    if flag in sys.argv:
        sys.argv.remove(flag)
        quiet = True
        break

gpodder_script = sys.argv[0]
gpodder_script = os.path.realpath(gpodder_script)
gpodder_dir = os.path.join(os.path.dirname(gpodder_script), '..')
# TODO: Read parent directory links as well (/bin -> /usr/bin, like on Fedora, see Bug #1618)
# This would allow /usr/share/gpodder/ (not /share/gpodder/) to be found from /bin/gpodder
prefix = os.path.abspath(os.path.normpath(gpodder_dir))

src_dir = os.path.join(prefix, 'src')

if os.path.exists(os.path.join(src_dir, 'gpodder', '__init__.py')):
    # Run gPodder from local source folder (not installed)
    sys.path.insert(0, src_dir)

import gpodder  # isort:skip

from gpodder import log  # isort:skip
log.setup(verbose, quiet)

from gpodder import common, core, download, feedcore, model, my, opml, sync, util, youtube  # isort:skip
from gpodder.config import config_value_to_string  # isort:skip
from gpodder.syncui import gPodderSyncUI  # isort:skip

_ = gpodder.gettext
N_ = gpodder.ngettext

gpodder.images_folder = os.path.join(prefix, 'share', 'gpodder', 'images')
gpodder.prefix = prefix

# This is the command-line UI variant
gpodder.ui.cli = True

have_ansi = sys.stdout.isatty() and not gpodder.ui.win32
interactive_console = sys.stdin.isatty() and sys.stdout.isatty()
is_single_command = False


def noop(*args, **kwargs):
    pass


def incolor(color_id, s):
    if have_ansi and cli._config.ui.cli.colors:
        return '\033[9%dm%s\033[0m' % (color_id, s)
    return s


# ANSI Colors: red = 1, green = 2, yellow = 3, blue = 4
inred, ingreen, inyellow, inblue = (functools.partial(incolor, x) for x in range(1, 5))


def FirstArgumentIsPodcastURL(function):
    """Decorator for functions that take a podcast URL as first arg"""
    setattr(function, '_first_arg_is_podcast', True)
    return function


def ExtensionsFunction(function):
    """Decorator for functions that take an extension as second arg"""
    setattr(function, '_first_arg_in', ('list', 'info', 'enable', 'disable'))
    setattr(function, '_second_arg_is_extension', True)
    return function


def get_terminal_size():
    if None in (termios, fcntl, struct):
        return (80, 24)

    s = struct.pack('HHHH', 0, 0, 0, 0)
    stdout = sys.stdout.fileno()
    x = fcntl.ioctl(stdout, termios.TIOCGWINSZ, s)
    rows, cols, xp, yp = struct.unpack('HHHH', x)
    return rows, cols


class gPodderCli(object):
    COLUMNS = 80
    EXIT_COMMANDS = ('quit', 'exit', 'bye')

    def __init__(self):
        self.core = core.Core()
        self._db = self.core.db
        self._config = self.core.config
        self._model = self.core.model

        self._current_action = ''
        self._commands = dict(
            (name.rstrip('_'), func)
            for name, func in inspect.getmembers(self)
            if inspect.ismethod(func) and not name.startswith('_'))
        self._prefixes, self._expansions = self._build_prefixes_expansions()
        self._prefixes.update({'?': 'help'})
        self._valid_commands = sorted(self._prefixes.values())
        gpodder.user_extensions.on_ui_initialized(
            self.core.model,
            self._extensions_podcast_update_cb,
            self._extensions_episode_download_cb)

    @contextlib.contextmanager
    def _action(self, msg):
        self._start_action(msg)
        try:
            yield
            self._finish_action()
        except Exception as ex:
            logger.warning('Action could not be completed', exc_info=True)
            self._finish_action(False)

    def _run_cleanups(self):
        # Find expired (old) episodes and delete them
        old_episodes = list(common.get_expired_episodes(self._model.get_podcasts(), self._config))
        if old_episodes:
            with self._action('Cleaning up old downloads'):
                for old_episode in old_episodes:
                    old_episode.delete_from_disk()

    def _build_prefixes_expansions(self):
        prefixes = {}
        expansions = collections.defaultdict(list)
        names = sorted(self._commands.keys())
        names.extend(self.EXIT_COMMANDS)

        # Generator for all prefixes of a given string (longest first)
        # e.g. ['gpodder', 'gpodde', 'gpodd', 'gpod', 'gpo', 'gp', 'g']
        def mkprefixes(n):
            return (n[:x] for x in range(len(n), 0, -1))

        # Return True if the given prefix is unique in "names"
        def is_unique(p):
            return len([n for n in names if n.startswith(p)]) == 1

        for name in names:
            is_still_unique = True
            unique_expansion = None
            for prefix in mkprefixes(name):
                if is_unique(prefix):
                    unique_expansion = '[%s]%s' % (prefix, name[len(prefix):])
                    prefixes[prefix] = name
                    continue

                if unique_expansion is not None:
                    expansions[prefix].append(unique_expansion)
                    continue

        return prefixes, expansions

    def _extensions_podcast_update_cb(self, podcast):
        self._info(_('Podcast update requested by extensions.'))
        self._update_podcast(podcast)

    def _extensions_episode_download_cb(self, episode):
        self._info(_('Episode download requested by extensions.'))
        self._download_episode(episode)

    def _start_action(self, msg):
        line = util.convert_bytes(msg)
        if len(line) > self.COLUMNS - 7:
            line = line[:self.COLUMNS - 7 - 3] + '...'
        else:
            line = line + (' ' * (self.COLUMNS - 7 - len(line)))
        self._current_action = line
        print(self._current_action, end='')

    def _update_action(self, progress):
        if have_ansi:
            progress = '%3.0f%%' % (progress * 100.,)
            result = '[' + inblue(progress) + ']'
            print('\r' + self._current_action + result, end='')

    def _finish_action(self, success=True, skip=False):
        if skip:
            result = '[' + inyellow('SKIP') + ']'
        elif success:
            result = '[' + ingreen('DONE') + ']'
        else:
            result = '[' + inred('FAIL') + ']'

        if have_ansi:
            print('\r' + self._current_action + result)
        else:
            print(result)
        self._current_action = ''

    def _atexit(self):
        self.core.shutdown()

    # -------------------------------------------------------------------

    def import_(self, url):
        for channel in opml.Importer(url).items:
            self.subscribe(channel['url'], channel.get('title'))

    def export(self, filename):
        podcasts = self._model.get_podcasts()
        opml.Exporter(filename).write(podcasts)

    def get_podcast(self, original_url, create=False, check_only=False):
        """Get a specific podcast by URL

        Returns a podcast object for the URL or None if
        the podcast has not been subscribed to.
        """
        url = util.normalize_feed_url(original_url)
        if url is None:
            self._error(_('Invalid url: %s') % original_url)
            return None

        # Check if it's a YouTube channel, user, or playlist and resolves it to its feed if that's the case
        url = youtube.parse_youtube_url(url)

        # Subscribe to new podcast
        if create:
            auth_tokens = {}
            while True:
                try:
                    return self._model.load_podcast(
                        url, create=True,
                        authentication_tokens=auth_tokens.get(url, None),
                        max_episodes=self._config.limit.episodes)
                except feedcore.AuthenticationRequired as e:
                    if e.url in auth_tokens:
                        print(inred(_('Wrong username/password')))
                        return None
                    else:
                        print(inyellow(_('Podcast requires authentication')))
                        print(inyellow(_('Please login to %s:') % (url,)))
                        username = input(_('User name:') + ' ')
                        if username:
                            password = input(_('Password:') + ' ')
                            if password:
                                auth_tokens[e.url] = (username, password)
                                url = e.url
                            else:
                                return None
                        else:
                            return None

        # Load existing podcast
        for podcast in self._model.get_podcasts():
            if podcast.url == url:
                return podcast

        if not check_only:
            self._error(_('You are not subscribed to %s.') % url)
        return None

    def subscribe(self, url, title=None):
        existing = self.get_podcast(url, check_only=True)
        if existing is not None:
            self._error(_('Already subscribed to %s.') % existing.url)
            return True

        try:
            podcast = self.get_podcast(url, create=True)
            if podcast is None:
                self._error(_('Cannot subscribe to %s.') % url)
                return True

            if title is not None:
                podcast.rename(title)
            podcast.save()
        except Exception as e:
            logger.warning('Cannot subscribe: %s', e, exc_info=True)
            if hasattr(e, 'strerror'):
                self._error(e.strerror)
            else:
                self._error(str(e))
            return True

        self._db.commit()

        self._info(_('Successfully added %s.' % url))
        return True

    def _print_config(self, search_for):
        for key in self._config.all_keys():
            if search_for is None or search_for.lower() in key.lower():
                value = config_value_to_string(self._config._lookup(key))
                print(key, '=', value)

    def set(self, key=None, value=None):
        if value is None:
            self._print_config(key)
            return

        try:
            current_value = self._config._lookup(key)
            current_type = type(current_value)
        except KeyError:
            self._error(_('This configuration option does not exist.'))
            return

        if current_type == dict:
            self._error(_('Can only set leaf configuration nodes.'))
            return

        self._config.update_field(key, value)
        self.set(key)

    @FirstArgumentIsPodcastURL
    def rename(self, url, title):
        podcast = self.get_podcast(url)

        if podcast is not None:
            old_title = podcast.title
            podcast.rename(title)
            self._db.commit()
            self._info(_('Renamed %(old_title)s to %(new_title)s.') % {
                'old_title': util.convert_bytes(old_title),
                'new_title': util.convert_bytes(title),
            })

        return True

    @FirstArgumentIsPodcastURL
    def unsubscribe(self, url):
        podcast = self.get_podcast(url)

        if podcast is None:
            self._error(_('You are not subscribed to %s.') % url)
        else:
            # Clean up downloads and download directories
            common.clean_up_downloads()

            podcast.delete()
            self._db.commit()
            self._error(_('Unsubscribed from %s.') % url)

            # Delete downloaded episodes
            podcast.remove_downloaded()

            # TODO: subscribe and unsubscribe need to sync with mygpo
            # Upload subscription list changes to the web service
#            self.mygpo_client.on_unsubscribe([podcast.url])

        return True

    def is_episode_new(self, episode):
        return (episode.state == gpodder.STATE_NORMAL and episode.is_new)

    def _episodesList(self, podcast, show_guid=False):
        def status_str(episode):
            # is new
            if self.is_episode_new(episode):
                return ' * '
            # is downloaded
            if (episode.state == gpodder.STATE_DOWNLOADED):
                return ' â–‰ '
            # is deleted
            if (episode.state == gpodder.STATE_DELETED):
                return ' â–‘ '

            return '   '

        def guid_str(episode):
            return ((' %s' % episode.guid) if show_guid else '')

        episodes = ('%3d.%s %s %s' % (i + 1, guid_str(e),
                                      status_str(e), e.title)
                    for i, e in enumerate(podcast.get_all_episodes()))
        return episodes

    @FirstArgumentIsPodcastURL
    def info(self, url):
        podcast = self.get_podcast(url)

        if podcast is None:
            self._error(_('You are not subscribed to %s.') % url)
        else:
            def feed_update_status_msg(podcast):
                if podcast.pause_subscription:
                    return "disabled"
                return "enabled"

            title, url, description, link, status = (
                podcast.title, podcast.url, podcast.description, podcast.link,
                feed_update_status_msg(podcast))
            description = '\n'.join(textwrap.wrap(description, subsequent_indent=' ' * 8))
            episodes = self._episodesList(podcast)
            episodes = '\n      '.join(episodes)
            self._pager("""
    Title: %(title)s
    URL: %(url)s
    Description:
        %(description)s
    Link: %(link)s
    Feed update is %(status)s

    Episodes:
      %(episodes)s
            """ % locals())

        return True

    @FirstArgumentIsPodcastURL
    def episodes(self, *args):
        show_guid = False
        args = list(args)
        # TODO: Start using argparse for things like that
        if '--guid' in args:
            args.remove('--guid')
            show_guid = True

        if len(args) > 1:
            self._error(_('Invalid command.'))
            return
        elif len(args) == 1:
            url = args[0]
            if url.startswith('-'):
                self._error(_('Invalid option: %s.') % (url,))
                return
        else:
            url = None

        output = []
        for podcast in self._model.get_podcasts():
            podcast_printed = False
            if url is None or podcast.url == url:
                episodes = self._episodesList(podcast, show_guid=show_guid)
                episodes = '\n      '.join(episodes)
                output.append("""
    Episodes from %s:
      %s
""" % (podcast.url, episodes))

        self._pager('\n'.join(output))
        return True

    def list(self):
        for podcast in self._model.get_podcasts():
            if not podcast.pause_subscription:
                print('#', ingreen(podcast.title))
            else:
                print('#', inred(podcast.title),
                      '-', _('Updates disabled'))

            print(podcast.url)

        return True

    def _update_podcast(self, podcast):
        with self._action(' %s' % podcast.title):
            podcast.update()

    def _pending_message(self, count):
        return N_('%(count)d new episode', '%(count)d new episodes',
                  count) % {'count': count}

    @FirstArgumentIsPodcastURL
    def update(self, url=None):
        count = 0
        print(_('Checking for new episodes'))
        for podcast in self._model.get_podcasts():
            if url is not None and podcast.url != url:
                continue

            if not podcast.pause_subscription:
                self._update_podcast(podcast)
                count += sum(1 for e in podcast.get_all_episodes() if self.is_episode_new(e))
            else:
                self._start_action(_('Skipping %(podcast)s') % {
                    'podcast': podcast.title})
                self._finish_action(skip=True)

        util.delete_empty_folders(gpodder.downloads)
        print(inblue(self._pending_message(count)))
        return True

    @FirstArgumentIsPodcastURL
    def pending(self, url=None):
        count = 0
        for podcast in self._model.get_podcasts():
            podcast_printed = False
            if url is None or podcast.url == url:
                for episode in podcast.get_all_episodes():
                    if self.is_episode_new(episode):
                        if not podcast_printed:
                            print('#', ingreen(podcast.title))
                            podcast_printed = True
                        print(' ', episode.title)
                        count += 1

        util.delete_empty_folders(gpodder.downloads)
        print(inblue(self._pending_message(count)))
        return True

    @FirstArgumentIsPodcastURL
    def partial(self, *args):
        def by_channel(e):
            return e.channel.title

        def guid_str(episode):
            return (('%s ' % episode.guid) if show_guid else '')

        def on_finish(resumable_episodes):
            count = len(resumable_episodes)
            resumable_episodes = sorted(resumable_episodes, key=by_channel)
            last_channel = None
            for e in resumable_episodes:
                if e.channel != last_channel:
                    print('#', ingreen(e.channel.title))
                    last_channel = e.channel
                print('  %s%s' % (guid_str(e), e.title))
            print(inblue(N_('%(count)d partial file',
                   '%(count)d partial files',
                   count) % {'count': count}))

        show_guid = '--guid' in args

        common.find_partial_downloads(self._model.get_podcasts(),
                                      noop,
                                      noop,
                                      noop,
                                      on_finish)
        return True

    def _download_episode(self, episode):
        with self._action('Downloading %s' % episode.title):
            if episode.download_task is None:
                task = download.DownloadTask(episode, self._config)
            else:
                task = episode.download_task
            task.add_progress_callback(self._update_action)
            task.status = download.DownloadTask.DOWNLOADING
            task.run()
            task.recycle()

    def _download_episodes(self, episodes):
        if self._config.downloads.chronological_order:
            # download older episodes first
            episodes = list(model.Model.sort_episodes_by_pubdate(episodes))

        if episodes:
            # Queue episodes to create partial files
            for e in episodes:
                if e.download_task is None:
                    download.DownloadTask(e, self._config)

            last_podcast = None
            for episode in episodes:
                if episode.channel != last_podcast:
                    print(inblue(episode.channel.title))
                    last_podcast = episode.channel
                self._download_episode(episode)

            util.delete_empty_folders(gpodder.downloads)
        print(len(episodes), 'episodes downloaded.')
        return True

    @FirstArgumentIsPodcastURL
    def download(self, url=None, guid=None):
        episodes = []
        for podcast in self._model.get_podcasts():
            if url is None or podcast.url == url:
                for episode in podcast.get_all_episodes():
                    if (not guid and self.is_episode_new(episode)) or (guid and episode.guid == guid):
                        episodes.append(episode)
        return self._download_episodes(episodes)

    @FirstArgumentIsPodcastURL
    def resume(self, guid=None):
        def guid_str(episode):
            return (('%s ' % episode.guid) if show_guid else '')

        def on_finish(episodes):
            if guid:
                episodes = [e for e in episodes if e.guid == guid]
            self._download_episodes(episodes)

        common.find_partial_downloads(self._model.get_podcasts(),
                                      noop,
                                      noop,
                                      noop,
                                      on_finish)
        return True

    @FirstArgumentIsPodcastURL
    def delete(self, url, guid):
        podcast = self.get_podcast(url)
        episode_to_delete = None

        if podcast is None:
            self._error(_('You are not subscribed to %s.') % url)
        else:
            for episode in podcast.get_all_episodes():
                if (episode.guid == guid):
                    episode_to_delete = episode

            if not episode_to_delete:
                self._error(_('No episode with the specified GUID found.'))
            else:
                if episode_to_delete.state != gpodder.STATE_DELETED:
                    episode_to_delete.delete_from_disk()
                    self._info(_('Deleted episode "%s".') % episode_to_delete.title)
                else:
                    self._error(_('Episode has already been deleted.'))

        return True

    @FirstArgumentIsPodcastURL
    def disable(self, url):
        podcast = self.get_podcast(url)

        if podcast is None:
            self._error(_('You are not subscribed to %s.') % url)
        else:
            if not podcast.pause_subscription:
                podcast.pause_subscription = True
                podcast.save()
            self._db.commit()
            self._error(_('Disabling feed update from %s.') % url)

        return True

    @FirstArgumentIsPodcastURL
    def enable(self, url):
        podcast = self.get_podcast(url)

        if podcast is None:
            self._error(_('You are not subscribed to %s.') % url)
        else:
            if podcast.pause_subscription:
                podcast.pause_subscription = False
                podcast.save()
            self._db.commit()
            self._error(_('Enabling feed update from %s.') % url)

        return True

    def youtube(self, url):
        fmt_ids = youtube.get_fmt_ids(self._config.youtube, False)
        yurl, duration = youtube.get_real_download_url(url, False, fmt_ids)
        if duration is not None:
            episode.total_time = int(int(duration) / 1000)
        print(yurl)

        return True

    def search(self, *terms):
        query = ' '.join(terms)
        if not query:
            return

        directory = my.Directory()
        results = directory.search(query)
        self._show_directory_results(results)

    def toplist(self):
        directory = my.Directory()
        results = directory.toplist()
        self._show_directory_results(results, True)

    def _show_directory_results(self, results, multiple=False):
        if not results:
            self._error(_('No podcasts found.'))
            return

        if not interactive_console or is_single_command:
            print('\n'.join(url for title, url in results))
            return

        def show_list():
            self._pager('\n'.join(
                '%3d: %s\n     %s' % (index + 1, title, url if title != url else '')
                for index, (title, url) in enumerate(results)))

        show_list()

        msg = _('Enter index to subscribe, ? for list')
        while True:
            index = input(msg + ': ')

            if not index:
                return

            if index == '?':
                show_list()
                continue

            try:
                index = int(index)
            except ValueError:
                self._error(_('Invalid value.'))
                continue

            if not (1 <= index <= len(results)):
                self._error(_('Invalid value.'))
                continue

            title, url = results[index - 1]
            self._info(_('Adding %s...') % title)
            self.subscribe(url)
            if not multiple:
                break

    @FirstArgumentIsPodcastURL
    def rewrite(self, old_url, new_url):
        podcast = self.get_podcast(old_url)
        if podcast is None:
            self._error(_('You are not subscribed to %s.') % old_url)
        else:
            result = podcast.rewrite_url(new_url)
            if result is None:
                self._error(_('Invalid URL: %s') % new_url)
            else:
                new_url = result
                self._error(_('Changed URL from %(old_url)s to %(new_url)s.') %
                            {'old_url': old_url,
                             'new_url': new_url, })
        return True

    def help(self):
        print(stylize(__doc__), file=sys.stderr, end='')
        return True

    def sync(self):
        def ep_repr(episode):
            return '{} / {}'.format(episode.channel.title, episode.title)

        def msg_title(title, message):
            if title:
                msg = '{}: {}'.format(title, message)
            else:
                msg = '{}'.format(message)
            return msg

        def _notification(message, title=None, important=False, widget=None):
            print(msg_title(message, title))

        def _show_confirmation(message, title=None):
            msg = msg_title(message, title)
            msg = _("%(title)s: %(msg)s ([yes]/no): ") % dict(title=title, msg=message)
            if not interactive_console:
                return True
            line = input(msg)
            return not line or (line.lower() == _('yes'))

        def _delete_episode_list(episodes, confirm=True, callback=None):
            if not episodes:
                return False

            episodes = [e for e in episodes if not e.archive]

            if not episodes:
                title = _('Episodes are locked')
                message = _(
                    'The selected episodes are locked. Please unlock the '
                    'episodes that you want to delete before trying '
                    'to delete them.')
                _notification(message, title)
                return False

            count = len(episodes)
            title = N_('Delete %(count)d episode?', 'Delete %(count)d episodes?',
                       count) % {'count': count}
            message = _('Deleting episodes removes downloaded files.')

            if confirm and not _show_confirmation(message, title):
                return False

            print(_('Please wait while episodes are deleted'))

            def finish_deletion(episode_urls, channel_urls):
                # Episodes have been deleted - persist the database
                self.db.commit()

            episode_urls = set()
            channel_urls = set()

            episodes_status_update = []
            for idx, episode in enumerate(episodes):
                if not episode.archive:
                    self._start_action(_('Deleting episode: %(episode)s') % {
                            'episode': episode.title})
                    episode.delete_from_disk()
                    self._finish_action(success=True)
                    episode_urls.add(episode.url)
                    channel_urls.add(episode.channel.url)
                    episodes_status_update.append(episode)

            # Notify the web service about the status update + upload
            if self.mygpo_client.can_access_webservice():
                self.mygpo_client.on_delete(episodes_status_update)
                self.mygpo_client.flush()

            if callback is None:
                util.idle_add(finish_deletion, episode_urls, channel_urls)
            else:
                util.idle_add(callback, episode_urls, channel_urls, None)

            return True

        def _episode_selector(parent_window, title=None, instructions=None, episodes=None,
                              selected=None, columns=None, callback=None, _config=None):
            if not interactive_console:
                return callback([e for i, e in enumerate(episodes) if selected[i]])

            def show_list():
                self._pager('\n'.join(
                    '[%s] %3d: %s' % (('X' if selected[index] else ' '), index + 1, ep_repr(e))
                    for index, e in enumerate(episodes)))

            print("{}. {}".format(title, instructions))
            show_list()

            msg = _('Enter episode index to toggle, ? for list, X to select all, space to select none, empty when ready')
            while True:
                index = input(msg + ': ')

                if not index:
                    return callback([e for i, e in enumerate(episodes) if selected[i]])

                if index == '?':
                    show_list()
                    continue
                elif index == 'X':
                    selected = [True, ] * len(episodes)
                    show_list()
                    continue
                elif index == ' ':
                    selected = [False, ] * len(episodes)
                    show_list()
                    continue
                else:
                    try:
                        index = int(index)
                    except ValueError:
                        self._error(_('Invalid value.'))
                        continue

                    if not (1 <= index <= len(episodes)):
                        self._error(_('Invalid value.'))
                        continue

                    e = episodes[index - 1]
                    selected[index - 1] = not selected[index - 1]
                    if selected[index - 1]:
                        self._info(_('Will delete %(episode)s') % dict(episode=ep_repr(e)))
                    else:
                        self._info(_("Won't delete %(episode)s") % dict(episode=ep_repr(e)))

        def _not_applicable(*args, **kwargs):
            pass

        def _mount_volume_for_file(file):
            result, message = util.mount_volume_for_file(file, None)
            if not result:
                self._error(_('mounting volume for file %(file)s failed with: %(error)s'
                    % dict(file=file.get_uri(), error=message)))
            return result

        class DownloadStatusModel(object):
            def register_task(self, ask):
                pass

        class DownloadQueueManager(object):
            def queue_task(x, task):
                def progress_updated(progress):
                    self._update_action(progress)
                with self._action(_('Syncing %s') % ep_repr(task.episode)):
                    task.status = sync.SyncTask.DOWNLOADING
                    task.add_progress_callback(progress_updated)
                    task.run()

                    if task.notify_as_finished():
                        if self._config.device_sync.after_sync.mark_episodes_played:
                            logger.info('Marking as played on transfer: %s', task.episode.url)
                            task.episode.mark(is_played=True)

                        if self._config.device_sync.after_sync.delete_episodes:
                            logger.info('Removing episode after transfer: %s', task.episode.url)
                            task.episode.delete_from_disk()

                    task.recycle()

        done_lock = threading.Lock()
        self.mygpo_client = my.MygPoClient(self._config)
        sync_ui = gPodderSyncUI(self._config,
                                _notification,
                                None,
                                _show_confirmation,
                                _not_applicable,
                                self._model.get_podcasts(),
                                DownloadStatusModel(),
                                DownloadQueueManager(),
                                _not_applicable,
                                self._db.commit,
                                _delete_episode_list,
                                _episode_selector,
                                _mount_volume_for_file)
        done_lock.acquire()
        sync_ui.on_synchronize_episodes(self._model.get_podcasts(), episodes=None, force_played=True, done_callback=done_lock.release)
        done_lock.acquire()  # block until done

    def _extensions_list(self):
        def by_category(ext):
            return ext.metadata.category

        def by_enabled_name(ext):
            return ('0' if ext.enabled else '1') + ext.name

        for cat, extensions in itertools.groupby(sorted(gpodder.user_extensions.get_extensions(), key=by_category), by_category):
            print(_(cat))
            for ext in sorted(extensions, key=by_enabled_name):
                if ext.enabled:
                    print('  ', inyellow(ext.name), ext.metadata.title, inyellow(_('(enabled)')))
                else:
                    print('  ', inblue(ext.name), ext.metadata.title)
        return True

    def _extensions_info(self, ext):
        if ext.enabled:
            print(inyellow(ext.name))
        else:
            print(inblue(ext.name))

        print(_('Title:'), ext.metadata.title)
        print(_('Category:'), _(ext.metadata.category))
        print(_('Description:'), ext.metadata.description)
        print(_('Authors:'), ext.metadata.authors)
        if ext.metadata.doc:
            print(_('Documentation:'), ext.metadata.doc)
        print(_('Enabled:'), _('yes') if ext.enabled else _('no'))

        return True

    def _extension_enable(self, container, new_enabled):
        if container.enabled == new_enabled:
            return True

        enabled_extensions = list(self._config.extensions.enabled)

        if new_enabled and container.name not in enabled_extensions:
            enabled_extensions.append(container.name)
        elif not new_enabled and container.name in enabled_extensions:
            enabled_extensions.remove(container.name)

        self._config.extensions.enabled = enabled_extensions

        now_enabled = (container.name in self._config.extensions.enabled)
        if new_enabled == now_enabled:
            if now_enabled:
                if getattr(container, 'on_ui_initialized', None) is not None:
                    container.on_ui_initialized(
                        self.core.model,
                        self._extensions_podcast_update_cb,
                        self._extensions_episode_download_cb)
            enabled_str = _('enabled') if now_enabled else _('disabled')
            self._info(
                inblue(
                    _('Extension %(name)s (%(title)s) %(enabled)s')
                    % dict(name=container.name, title=container.metadata.title, enabled=enabled_str)))
        elif container.error is not None:
            if hasattr(container.error, 'message'):
                error_msg = container.error.message
            else:
                error_msg = str(container.error)
            self._error(_('Extension cannot be activated'))
            self._error(error_msg)
        return True

    @ExtensionsFunction
    def extensions(self, action='list', extension_name=None):
        if action in ('enable', 'disable', 'info'):
            if not extension_name:
                print(inred('E: extensions {} missing the extension name').format(action))
                return False
            extension = None
            for ext in gpodder.user_extensions.get_extensions():
                if ext.name == extension_name:
                    extension = ext
                    break
            if not extension:
                print(inred('E: extensions {} called with unknown extension name "{}"').format(action, extension_name))
                return False

        if action == 'list':
            return self._extensions_list()
        elif action in ('enable', 'disable'):
            self._extension_enable(extension, action == 'enable')
        elif action == 'info':
            self._extensions_info(extension)
        return True
    # -------------------------------------------------------------------

    def _pager(self, output):
        if have_ansi:
            # Need two additional rows for command prompt
            rows_needed = len(output.splitlines()) + 2
            rows, cols = get_terminal_size()
            if rows_needed < rows:
                print(output)
            else:
                pydoc.pager(output)
        else:
            print(output)

    def _shell(self):
        print(os.linesep.join(x.strip() for x in ("""
        gPodder %(__version__)s (%(__date__)s) - %(__url__)s
        %(__copyright__)s
        License: %(__license__)s

        Entering interactive shell. Type 'help' for help.
        Press Ctrl+D (EOF) or type 'quit' to quit.
        """ % gpodder.__dict__).splitlines()))

        cli._run_cleanups()

        if readline is not None:
            readline.parse_and_bind('tab: complete')
            readline.set_completer(self._tab_completion)
            readline.set_completer_delims(' ')

        while True:
            try:
                line = input('gpo> ')
            except EOFError:
                print('')
                break
            except KeyboardInterrupt:
                print('')
                continue

            if self._prefixes.get(line, line) in self.EXIT_COMMANDS:
                break

            try:
                args = shlex.split(line)
            except ValueError as value_error:
                self._error(_('Syntax error: %(error)s') %
                            {'error': value_error})
                continue

            try:
                self._parse(args)
            except KeyboardInterrupt:
                self._error('Keyboard interrupt.')
            except EOFError:
                self._error('EOF.')

        self._atexit()

    def _error(self, *args):
        print(inred(' '.join(args)), file=sys.stderr)

    # Warnings look like error messages for now
    _warn = _error

    def _info(self, *args):
        print(*args)

    def _checkargs(self, func, command_line):
        argspec = inspect.getfullargspec(func)
        assert not argspec.kwonlyargs  # keyword-only arguments are unsupported
        args, varargs, keywords, defaults = argspec.args, argspec.varargs, argspec.varkw, argspec.defaults
        args.pop(0)  # Remove "self" from args
        defaults = defaults or ()
        minarg, maxarg = len(args) - len(defaults), len(args)

        if (len(command_line) < minarg
                or (len(command_line) > maxarg and varargs is None)):
            self._error('Wrong argument count for %s.' % func.__name__)
            return False

        return func(*command_line)

    def _tab_completion_podcast(self, text, count):
        """Tab completion for podcast URLs"""
        urls = [p.url for p in self._model.get_podcasts() if text in p.url]
        if count < len(urls):
            return urls[count]

        return None

    def _tab_completion_in(self, text, count, choices):
        """Tab completion for a list of choices"""
        compat_choices = [c for c in choices if text in c]
        if count < len(compat_choices):
            return compat_choices[count]

        return None

    def _tab_completion_extensions(self, text, count):
        """Tab completion for extension names"""
        exts = [e.name for e in gpodder.user_extensions.get_extensions() if text in e.name]
        if count < len(exts):
            return exts[count]

        return None

    def _tab_completion(self, text, count):
        """Tab completion function for readline"""
        if readline is None:
            return None

        current_line = readline.get_line_buffer()
        if text == current_line:
            for name in self._valid_commands:
                if name.startswith(text):
                    if count == 0:
                        return name
                    else:
                        count -= 1
        else:
            args = current_line.split()
            command = args.pop(0)
            command_function = getattr(self, command, None)
            if not command_function:
                return None
            if getattr(command_function, '_first_arg_is_podcast', False):
                if not args or (len(args) == 1 and not current_line.endswith(' ')):
                    return self._tab_completion_podcast(text, count)
            first_in = getattr(command_function, '_first_arg_in', False)
            if first_in:
                if not args or (len(args) == 1 and not current_line.endswith(' ')):
                    return self._tab_completion_in(text, count, first_in)
            snd_ext = getattr(command_function, '_second_arg_is_extension', False)
            if snd_ext:
                if (len(args) > 0 and len(args) < 2 and args[0] != 'list') or (len(args) == 2 and not current_line.endswith(' ')):
                    return self._tab_completion_extensions(text, count)

        return None

    def _parse_single(self, command_line):
        try:
            result = self._parse(command_line)
        except KeyboardInterrupt:
            self._error('Keyboard interrupt.')
            result = -1
        self._atexit()
        return result

    def _parse(self, command_line):
        if not command_line:
            return False

        command = command_line.pop(0)

        # Resolve command aliases
        command = self._prefixes.get(command, command)

        if command in self._commands:
            func = self._commands[command]
            if inspect.ismethod(func):
                return self._checkargs(func, command_line)

        if command in self._expansions:
            print(_('Ambiguous command. Did you mean..'))
            for cmd in self._expansions[command]:
                print('   ', inblue(cmd))
        else:
            self._error(_('The requested function is not available.'))

        return False


def stylize(s):
    s = re.sub(r'    .{27}', lambda m: inblue(m.group(0)), s)
    s = re.sub(r'  - .*', lambda m: ingreen(m.group(0)), s)
    return s


def main():
    global logger, cli
    logger = logging.getLogger(__name__)
    cli = gPodderCli()
    msg = model.check_root_folder_path()
    if msg:
        print(msg, file=sys.stderr)
    args = sys.argv[1:]
    if args:
        is_single_command = True
        cli._run_cleanups()
        cli._parse_single(args)
    elif interactive_console:
        cli._shell()
    else:
        print(__doc__, end='')


if __name__ == '__main__':
    main()