~mterry/podbird/theme-colors

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
/*
 * Copyright 2015-2016 Podbird Team
 *
 * This file is part of Podbird.
 *
 * Podbird 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; version 3.
 *
 * Podbird is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import QtQuick 2.4
import QtMultimedia 5.6
import Ubuntu.Components 1.3
import QtQuick.LocalStorage 2.0
import Ubuntu.DownloadManager 1.2
import Ubuntu.Components.Popups 1.3
import "../podcasts.js" as Podcasts
import "../components"

Page {
    id: episodesPage

    visible: false

    property string episodeName
    property string episodeId
    property string episodeArtist
    property string episodeImage
    property string tempGuid: "NULL"
    property string mode: "listened"

    property bool episodesUpdating: false;

    Component.onCompleted: {
        loadEpisodes(episodeId, episodeArtist, episodeImage)
        if (downloader.downloadingGuid != "")
            tempGuid = downloader.downloadingGuid
    }

    header: standardHeader

    PageHeader {
        id: standardHeader
        title: i18n.tr("Podcast")
        flickable: null

        trailingActionBar.actions: [
            Action {
                iconName: "search"
                text: i18n.tr("Search Episode")
                onTriggered: {
                    episodesPage.header = searchHeader
                    searchField.item.forceActiveFocus()
                }
            },

            Action {
                text: i18n.tr("Unsubscribe")
                iconName: "delete"
                onTriggered: {
                    PopupUtils.open(confirmDeleteDialog, episodesPage);
                }
            }
        ]
    }

    PageHeader {
        id: searchHeader
        visible: episodesPage.header === searchHeader
        flickable: null

        leadingActionBar.actions: Action {
            iconName: "back"
            onTriggered: {
                episodeList.forceActiveFocus()
                episodesPage.header = standardHeader
                episodeList.positionViewAtBeginning()
            }
        }

        contents: Loader {
            id: searchField
            sourceComponent: episodesPage.header === searchHeader ? searchFieldComponent : undefined
            anchors.left: parent ? parent.left : undefined
            anchors.right: parent ? parent.right : undefined
            anchors.verticalCenter: parent ? parent.verticalCenter : undefined
        }
    }

    PageHeader {
        id: selectionHeader
        visible: episodeList.ViewItems.selectMode
        // TRANSLATORS: This is the page title. Keep it short. Otherwise it will just be elided.
        title: i18n.tr("%1 item selected", "%1 items selected", episodeList.ViewItems.selectedIndices.length).arg(episodeList.ViewItems.selectedIndices.length)

        onVisibleChanged: {
            if (visible) {
                episodesPage.header = selectionHeader
            }
        }

        leadingActionBar.actions: [
            Action {
                iconName: "back"
                text: i18n.tr("Back")
                onTriggered: {
                    episodeList.closeSelection()
                }
            }
        ]

        trailingActionBar {
            numberOfSlots: 6
            actions: [
                Action {
                    iconName: "select"
                    text: i18n.tr("Mark Listened")
                    enabled: episodeList.ViewItems.selectedIndices.length !== 0
                    visible: episodesPage.mode !== "listened"
                    onTriggered: {
                        var db = Podcasts.init();
                        db.transaction(function (tx) {
                            for (var i=0; i<episodeList.ViewItems.selectedIndices.length; i++) {
                                var index = episodeList.ViewItems.selectedIndices[i]
                                tx.executeSql("UPDATE Episode SET listened=1 WHERE guid=?", [episodeModel.get(index).guid]);
                            }
                        });

                        refreshModel();
                        episodeList.closeSelection()
                    }
                },

                Action {
                    iconName: "save"
                    text: i18n.tr("Download episode(s)")
                    enabled: episodeList.ViewItems.selectedIndices.length !== 0
                    visible: episodesPage.mode !== "downloaded"

                    onTriggered: {
                        var db = Podcasts.init();
                        db.transaction(function (tx) {
                            for (var i=0; i<episodeList.ViewItems.selectedIndices.length; i++) {
                                var index = episodeList.ViewItems.selectedIndices[i]
                                if (!episodeModel.get(index).downloadedfile) {
                                    episodeModel.setProperty(index, "queued", 1)
                                    tx.executeSql("UPDATE Episode SET queued=1 WHERE guid = ?", [episodeModel.get(index).guid]);
                                    if (episodeModel.get(index).audiourl) {
                                        podbird.downloadEpisode(episodeModel.get(index).image, episodeModel.get(index).name, episodeModel.get(index).guid, episodeModel.get(index).audiourl)
                                    } else {
                                        console.log("[ERROR]: Invalid download url: " + episodeModel.get(index).audiourl)
                                    }
                                }
                            }
                        });

                        refreshModel();
                        episodeList.closeSelection()
                    }
                },

                Action {
                    iconName: "delete"
                    text: i18n.tr("Delete episode(s)")
                    enabled: episodeList.ViewItems.selectedIndices.length !== 0

                    onTriggered: {
                        var db = Podcasts.init();
                        db.transaction(function (tx) {
                            for (var i=0; i<episodeList.ViewItems.selectedIndices.length; i++) {
                                var index = episodeList.ViewItems.selectedIndices[i]
                                if (episodeModel.get(index).downloadedfile) {
                                    fileManager.deleteFile(episodeModel.get(index).downloadedfile);
                                    tx.executeSql("UPDATE Episode SET downloadedfile = NULL WHERE guid = ?", [episodeModel.get(index).guid]);
                                    episodeModel.setProperty(index, "downloadedfile", "")
                                }
                            }
                        });

                        refreshModel();
                        episodeList.closeSelection()
                    }
                },

                Action {
                    iconName: "like"
                    text: i18n.tr("Favourite episode(s)")
                    enabled: episodeList.ViewItems.selectedIndices.length !== 0

                    onTriggered: {
                        var db = Podcasts.init();
                        db.transaction(function (tx) {
                            for (var i=0; i<episodeList.ViewItems.selectedIndices.length; i++) {
                                var index = episodeList.ViewItems.selectedIndices[i]
                                if (!episodeModel.get(index).favourited) {
                                    tx.executeSql("UPDATE Episode SET favourited=1 WHERE guid=?", [episodeModel.get(index).guid])
                                    episodeModel.setProperty(index, "favourited", 1)
                                }
                            }
                        });

                        refreshModel();
                        episodeList.closeSelection()
                    }
                },

                Action {
                    iconName: "add-to-playlist"
                    text: i18n.tr("Add to queue")
                    enabled: episodeList.ViewItems.selectedIndices.length !== 0

                    onTriggered: {
                        for (var i=0; i<episodeList.ViewItems.selectedIndices.length; i++) {
                            var index = episodeList.ViewItems.selectedIndices[i]
                            if (episodeModel.get(index).audiourl) {
                                var url = episodeModel.get(index).downloadedfile ? "file://" + episodeModel.get(index).downloadedfile : episodeModel.get(index).audiourl
                                player.addEpisodeToQueue(episodeModel.get(index).guid, episodeModel.get(index).image, episodeModel.get(index).name, episodeModel.get(index).artist, url)
                            }
                        }

                        episodeList.closeSelection()
                    }
                }
            ]
        }
    }

    onVisibleChanged: {
        if (!visible) {
            state = "default";
        }
    }

    Component {
        id: searchFieldComponent
        TextField {
            inputMethodHints: Qt.ImhNoPredictiveText
            placeholderText: i18n.tr("Search episode")
        }
    }

    Connections {
        target: downloader
        onDownloadingGuidChanged: {
            var db = Podcasts.init();
            db.transaction(function (tx) {
                /*
                 If tempGuid is NULL, then the episode currently being downloaded is not found within
                 this podcast. On the other hand, if it is within this podcast, then update the episodeModel
                 with the downloadedfile location we just received from the downloader.
                */
                if (tempGuid != "NULL") {
                    var rs2 = tx.executeSql("SELECT downloadedfile, podcast FROM Episode WHERE guid=?", [tempGuid]);
                    for (var i=0; i<episodeModel.count; i++) {
                        if (episodeModel.get(i).guid == tempGuid) {
                            console.log("[LOG]: Setting episode download URL to " + rs2.rows.item(0).downloadedfile)
                            episodeModel.setProperty(i, "downloadedfile", rs2.rows.item(0).downloadedfile)
                            break
                        }
                    }
                    tempGuid = "NULL"
                }

                /*
                 Here it is checked if the currently downloaded episode belongs to the podcast
                 page being currently displayed. If it is, then the downloaded episode guid is
                 stored in the tempGuid variable to track it.
                */
                var rs = tx.executeSql("SELECT podcast FROM Episode WHERE guid=?", [downloader.downloadingGuid]);

                if (downloader.downloadingGuid != "" && rs.rows.item(0).podcast == episodeId && tempGuid == "NULL") {
                    tempGuid = downloader.downloadingGuid
                }
            });
            refreshModel();
        }
    }

    Component {
        id: confirmDeleteDialog
        Dialog {
            id: dialogInternal
            title: i18n.tr("Unsubscribe Confirmation")
            text: i18n.tr("Are you sure you want to unsubscribe from <b>%1</b>?").arg(episodesPage.episodeName)
            Button {
                text: i18n.tr("Unsubscribe")
                color: theme.palette.normal.negative
                onClicked: {
                    var db = Podcasts.init();
                    db.transaction(function (tx) {
                        var rs = tx.executeSql("SELECT downloadedfile FROM Episode WHERE downloadedfile NOT NULL AND podcast=?", [episodeId]);
                        for(var i = 0; i < rs.rows.length; i++) {
                            fileManager.deleteFile(rs.rows.item(i).downloadedfile);
                        }
                        tx.executeSql("DELETE FROM Episode WHERE podcast=?", [episodeId]);
                        tx.executeSql("DELETE FROM Podcast WHERE rowid=?", [episodeId]);
                        mainStack.pop()
                        PopupUtils.close(dialogInternal)
                    });
                }
            }
            Button {
                text: i18n.tr("Cancel")
                onClicked: {
                    PopupUtils.close(dialogInternal)
                }
            }
        }
    }

    /*
     Note (nik90): After the upgrade to Ubuntu.Components 1.2, it seems the new listitems don't have their trailing
     action width clamped. As a result when the list item expands and the user swipes left, it leads to a rather huge
     trailing edge action. This has been reported upstream at http://pad.lv/1465582. Until this is fixed, the
     episode description is shown in a dialog.
    */
    Component {
        id: episodeDescriptionDialog
        Dialog {
            id: dialogInternal

            property string description

            title: "<b>%1</b>".arg(i18n.tr("Episode Description"))

            Label {
                width: parent.width
                wrapMode: Text.WordWrap
                color: theme.palette.normal.overlayText
                linkColor: podbird.appTheme.linkText
                text: dialogInternal.description
                onLinkActivated: Qt.openUrlExternally(link)
            }

            Button {
                text: i18n.tr("Close")
                color: theme.palette.normal.positive
                onClicked: {
                    PopupUtils.close(dialogInternal)
                }
            }
        }
    }

    Loader {
        id: emptyState

        anchors {
            left: parent.left
            right: parent.right
            margins: units.gu(2)
            verticalCenter: parent.verticalCenter
            verticalCenterOffset: Qt.inputMethod.visible ? units.gu(4) : 0
        }

        sourceComponent: (episodesPage.header === searchHeader && sortedEpisodeModel.count === 0) ? emptyStateComponent
                                                                                                  : undefined
    }

    Component {
        id: emptyStateComponent
        EmptyState {
            icon.source: Qt.resolvedUrl("../graphics/notFound.svg")
            title: i18n.tr("No episodes found")
            subTitle: i18n.tr("No episodes found matching the search term.")
        }
    }

    ListModel {
        id: episodeModel
    }

    SortFilterModel {
        id: sortedEpisodeModel
        model: episodeModel
        filter.property: "name"
        filter.pattern: episodesPage.header === searchHeader && searchField.status == Loader.Ready ? RegExp(searchField.item.text, "gi")
                                                                                                   : RegExp("", "gi")
    }

    ListView {
        id: episodeList

        signal clearSelection()
        signal closeSelection()

        Component.onCompleted: {
            // FIXME: workaround for qtubuntu not returning values depending on the grid unit definition
            // for Flickable.maximumFlickVelocity and Flickable.flickDeceleration
            var scaleFactor = units.gridUnit / 8;
            maximumFlickVelocity = maximumFlickVelocity * scaleFactor;
            flickDeceleration = flickDeceleration * scaleFactor;
        }

        anchors { fill: parent; topMargin: episodesPage.header.height }
        model: sortedEpisodeModel
        clip: true

        header: Column {
            height: coverArtContainer.height + modeTabs.height + units.gu(2)
            Item {
                id: coverArtContainer

                width: episodesPage.width
                visible: episodesPage.header !== searchHeader && sortedEpisodeModel.count !== 0
                height: episodesPage.header !== searchHeader && sortedEpisodeModel.count !== 0 ? cover.height + units.gu(6) : 0

                Image {
                    id:cover
                    width: units.gu(18)
                    height: width
                    sourceSize.height: width
                    sourceSize.width: width
                    source: episodeImage
                    asynchronous: true
                    anchors {
                        horizontalCenter: parent.horizontalCenter
                        top: parent.top
                        margins: units.gu(2)
                    }
                }

                Label {
                    text: episodeName
                    width: parent.width
                    wrapMode: Text.WordWrap
                    horizontalAlignment: Text.AlignHCenter
                    maximumLineCount: 2
                    elide: Text.ElideRight
                    color: theme.palette.normal.backgroundText
                    anchors.top: cover.bottom
                    anchors.topMargin: units.gu(2)
                }
            }

            Item {
                width: parent.width
                height: units.gu(2)
            }

            Item {
                id: modeTabs
                height: unheardTab.implicitHeight + units.gu(2.25)
                width: episodesPage.width

                Rectangle {
                    id: sliderContainer
                    anchors.top: unheardTab.bottom
                    anchors.topMargin: units.gu(1)
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.margins: units.gu(2)
                    height: units.gu(0.25)
                    radius: width/3
                    color: theme.palette.normal.base
                }

                Rectangle {
                    id: slider
                    anchors.top: unheardTab.bottom
                    anchors.topMargin: units.gu(1)
                    height: units.gu(0.25)
                    radius: width/3
                    width: sliderContainer.width/3
                    color: theme.palette.normal.positionText
                    x: {
                        if (episodesPage.mode === "unheard")
                            return units.gu(2)
                        else if (episodesPage.mode === "listened")
                            return width + units.gu(2)
                        else
                            return 2 * width + units.gu(2)
                    }

                    Behavior on x {
                        UbuntuNumberAnimation {}
                    }
                }

                Label {
                    id: unheardTab
                    text: i18n.tr("Unheard")
                    anchors.left: parent.left
                    anchors.leftMargin: units.gu(2)
                    width: sliderContainer.width/3
                    horizontalAlignment: Text.AlignHCenter
                    font.weight: Font.DemiBold
                    color: episodesPage.mode == "unheard" ? theme.palette.normal.positionText : theme.palette.normal.backgroundTertiaryText

                    AbstractButton {
                        anchors.fill: parent
                        onClicked: episodesPage.mode = "unheard"
                    }
                }

                Label {
                    id: listenedTab
                    anchors.left: unheardTab.right
                    text: i18n.tr("Listened")
                    width: sliderContainer.width/3
                    font.weight: Font.DemiBold
                    horizontalAlignment: Text.AlignHCenter
                    color: episodesPage.mode == "listened" ? theme.palette.normal.positionText : theme.palette.normal.backgroundTertiaryText

                    AbstractButton {
                        anchors.fill: parent
                        onClicked: episodesPage.mode = "listened"
                    }
                }

                Label {
                    id: downloadedTab
                    anchors.right: parent.right
                    anchors.rightMargin: units.gu(2)
                    width: sliderContainer.width/3
                    font.weight: Font.DemiBold
                    horizontalAlignment: Text.AlignHCenter
                    text: i18n.tr("Downloaded")
                    color: episodesPage.mode == "downloaded" ? theme.palette.normal.positionText : theme.palette.normal.backgroundTertiaryText

                    AbstractButton {
                        anchors.fill: parent
                        onClicked: episodesPage.mode = "downloaded"
                    }
                }
            }

        }

        footer: Item {
            width: parent.width
            height: units.gu(8)
        }

        delegate: ListItem {
            id: listItem

            divider.visible: false
            highlightColor: theme.palette.selected.background
            height: visible ? listItemLayout.height + progressBarLoader.height + units.gu(1) : 0

            visible: episodesPage.mode == "listened" ? model.listened
                                                     : (episodesPage.mode == "unheard" ? !model.listened
                                                                                       : model.downloadedfile ? true : false)

            ListItemLayout {
                id: listItemLayout

                title.text: model.name !== undefined ? model.name.trim() : "Undefined"
                title.color: downloader.downloadingGuid === model.guid ? theme.palette.normal.positionText
                                                                       : theme.palette.normal.backgroundText
                // #FIXME: Change this 2 to prevent title eliding when UITK is updated to rev > 1800
                title.maximumLineCount: 1

                subtitle.text: model.duration === 0 || model.duration === undefined ? model.downloadedfile ? "📎 " + Qt.formatDate(new Date(model.published), "MMM d, yyyy")
                                                                                                           : Qt.formatDate(new Date(model.published), "MMM d, yyyy")
                                                                                    : model.downloadedfile ? "📎 " + Podcasts.formatEpisodeTime(model.duration) + " | " + Qt.formatDate(new Date(model.published), "MMM d, yyyy")
                                                                                                           : Podcasts.formatEpisodeTime(model.duration) + " | " + Qt.formatDate(new Date(model.published), "MMM d, yyyy")

                padding.top: units.gu(1)
                padding.bottom: units.gu(0.5)
            }

            Loader {
                id: progressBarLoader
                anchors { top: listItemLayout.bottom; left: parent.left; right: parent.right; leftMargin: units.gu(2); rightMargin: units.gu(2) }
                height: downloader.downloadingGuid === model.guid ? units.dp(5) : 0
                visible: sourceComponent !== undefined
                sourceComponent: downloader.downloadingGuid === model.guid ? progressBar : undefined
            }

            Component {
                id: progressBar
                CustomProgressBar {
                    indeterminateProgress: downloader.progress < 0 || downloader.progress > 100 && downloader.downloadingGuid === model.guid
                    progress: downloader.progress
                }
            }

            trailingActions: ListItemActions {
                actions: [
                    Action {
                        iconName: model.listened ? "view-collapse" : "select"
                        onTriggered: {
                            var db = Podcasts.init();
                            db.transaction(function (tx) {
                                if (model.listened)
                                    tx.executeSql("UPDATE Episode SET listened=0 WHERE guid=?", [model.guid])
                                else
                                    tx.executeSql("UPDATE Episode SET listened=1 WHERE guid=?", [model.guid])
                                refreshModel();
                            });
                        }
                    },

                    Action {
                        enabled: downloader.downloadingGuid !== model.guid
                        iconName: model.downloadedfile ? "delete" : (model.queued && downloader.downloadingGuid !== model.guid ? "history" : "save")
                        onTriggered: {
                            var db = Podcasts.init();
                            if (model.downloadedfile) {
                                fileManager.deleteFile(model.downloadedfile);
                                db.transaction(function (tx) {
                                    tx.executeSql("UPDATE Episode SET downloadedfile = NULL WHERE guid = ?", [model.guid]);
                                });
                                episodeModel.setProperty(model.index, "downloadedfile", "")
                            } else {
                                db.transaction(function (tx) {
                                    tx.executeSql("UPDATE Episode SET queued=1 WHERE guid = ?", [model.guid]);
                                });
                                episodeModel.setProperty(model.index, "queued", 1)
                                if (model.audiourl) {
                                    podbird.downloadEpisode(model.image, model.name, model.guid, model.audiourl)
                                } else {
                                    console.log("[ERROR]: Invalid download url: " + model.audiourl)
                                }
                            }
                        }
                    },

                    Action {
                        iconName: "add-to-playlist"
                        onTriggered: {
                            var url = model.downloadedfile ? "file://" + model.downloadedfile : model.audiourl
                            player.addEpisodeToQueue(model.guid, model.image, model.name, model.artist, url)
                        }
                    },

                    Action {
                        iconName: model.favourited ? "unlike" : "like"
                        onTriggered: {
                            var db = Podcasts.init();
                            db.transaction(function (tx) {
                                if (model.favourited)
                                    tx.executeSql("UPDATE Episode SET favourited=0 WHERE guid=?", [model.guid])
                                else
                                    tx.executeSql("UPDATE Episode SET favourited=1 WHERE guid=?", [model.guid])
                                refreshModel();
                            });
                        }
                    },

                    Action {
                        iconName: "info"
                        onTriggered: {
                            var popup = PopupUtils.open(episodeDescriptionDialog, episodesPage);
                            popup.description = model.description
                        }
                    }
                ]
            }

            onClicked: {
                Haptics.play()
                if (selectMode) {
                    selected = !selected
                } else {
                    if (currentGuid !== model.guid) {
                        currentUrl = model.downloadedfile ? "file://" + model.downloadedfile : model.audiourl;
                        player.playEpisode(model.guid, model.image, model.name, model.artist, currentUrl)
                    }
                }
            }

            onPressAndHold: {
                ListView.view.ViewItems.selectMode = !ListView.view.ViewItems.selectMode
            }
        }

        onClearSelection: {
            ViewItems.selectedIndices = []
        }

        onCloseSelection: {
            clearSelection()
            ViewItems.selectMode = false
            episodesPage.header = standardHeader
        }

        PullToRefresh {
            refreshing: episodesUpdating
            onRefresh: updateEpisodesDatabase();
        }

        Scrollbar {
            flickableItem: episodeList
            align: Qt.AlignTrailing
        }
    }

    function refreshModel() {
        var db = Podcasts.init();
        loadEpisodes(episodeId, episodeArtist, episodeImage);
        episodesUpdating = false;
    }

    function loadEpisodes(pid, artist, img) {
        var i, episode;
        var newCount = 0;

        episodeModel.clear();

        var db = Podcasts.init();
        db.transaction(function (tx) {
            var rs = tx.executeSql("SELECT rowid, * FROM Episode WHERE podcast=? ORDER BY published DESC", [pid]);
            for(i = 0; i < rs.rows.length; i++) {
                episode = rs.rows.item(i);
                if (!episode.listened) {
                    episodeModel.insert(newCount, {"guid" : episode.guid, "listened" : episode.listened, "published": episode.published, "name" : episode.name, "description" : episode.description, "duration" : episode.duration, "position" : episode.position, "downloadedfile" : episode.downloadedfile, "image" : img, "artist" : artist, "audiourl" : episode.audiourl, "queued": episode.queued, "favourited": episode.favourited});
                    newCount++;
                } else {
                    episodeModel.insert(i,{"guid" : episode.guid, "listened" : episode.listened, "published": episode.published, "name" : episode.name, "description" : episode.description, "duration" : episode.duration, "position" : episode.position, "downloadedfile" : episode.downloadedfile, "image" : img, "artist" : artist, "audiourl" : episode.audiourl, "queued": episode.queued, "favourited": episode.favourited});
                }
            }
        });
    }

    function updateEpisodesDatabase() {
        episodesUpdating = true;
        Podcasts.updateEpisodes(refreshModel)
    }
}