aboutsummaryrefslogtreecommitdiffhomepage
path: root/js/main.js
blob: 0025137f8ffa8bd5f7094d2d6f7063f6bda1be2c (plain)
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
// Variables for the Authorised Devices card
var clientIdentifier; // UID for the device being used
var plexProduct = "PASTA"; // X-Plex-Product - Application name
var pastaVersion = "1.2.2"; // X-Plex-Version - Application version
var pastaPlatform; // X-Plex-Platform - Web Browser
var pastaPlatformVersion; // X-Plex-Platform-Version - Web Browser version
var deviceInfo; // X-Plex-Device - Operation system?
var deviceName; // X-Plex-Device-Name - Main name shown
// End auth devices card variables
var plexUrl;
var plexToken;
var backOffTimer = 0;
var serverList = []; // save server information for pin login and multiple servers

var libraryNumber = ""; // The Library ID that was clicked
var showId = ""; // Stores the Id for the most recently clicked series
var seasonsList = []; // Stores the Ids for all seasons of the most recently clicked series
var seasonId = ""; // Store the Id of the most recently clicked season
var episodeId = ""; // Stores the Id of the most recently clicked episode

$(document).ready(() => {
    // Check if there is a page refresh, if so we want to push the history without the #
    let navigationType = performance.getEntriesByType("navigation")[0].type;
    if ((navigationType == 'reload') && (window.location.href.indexOf('#authentication') == -1)) {
        window.history.pushState('', document.title, window.location.pathname + '#authentication');
    }

    // Enable Tooltips
    $('#helpAboutIcon, #titleLogo').tooltip();

    // Enable history tracking for tabs
    $('a[data-toggle="tab"]').historyTabs();

    // Check if the page was loaded locally or over http and warn them about the value of https
    if ((location.protocol == "http:") || (location.protocol == "file:")) {
        if (localStorage.showHttpAlert == 'false') {

        }
        else {
            $("#insecureWarning").show();
        }
    }
    // SET THE VARIABLES FOR PLEX PIN AUTH REQUESTS
    try {
        let browserInfo = getBrowser();
        // Set the clientID, this might get overridden if one is saved to localstorage
        clientIdentifier = `PASTA-cglatot-${Date.now()}-${Math.round(Math.random() * 1000)}`;
        // Set the OS
        deviceInfo = browserInfo.os || "";
        // Set the web browser and version
        pastaPlatform = browserInfo.browser || "";
        pastaPlatformVersion = browserInfo.browserVersion || "";
        // Set the main display name
        deviceName = `PASTA (${pastaPlatform})` || "PASTA";
    } catch (e) {
        console.log(e);
        // Fallback values
        // Set the clientID, this might get overridden if one is saved to localstorage
        clientIdentifier = `PASTA-cglatot-${Date.now()}-${Math.round(Math.random() * 1000)}`;
        // Set the OS
        deviceInfo = "";
        // Set the web browser and version
        pastaPlatform = "";
        pastaPlatformVersion = "";
        // Set the main display name
        deviceName = "PASTA";
    }

    // Validation listeners on the Plex URL Input
    $('#plexUrl').on("input", () => {
        validateEnableConnectBtn('plexUrl');
    });

    // Validation listeners on the Plex Token Input
    $('#plexToken').on("input", () => {
        validateEnableConnectBtn('plexToken');
    });

    // Setup on change listener for toggle buttons
    $('input[type=radio][name=pinOrAuth]').change(function() {
        toggleAuthPages(this.value);
    });

    if (!localStorage.isPinAuth) {
        // Not using PIN auth, so must be using url / token
        if (localStorage.plexUrl && localStorage.plexUrl !== "") {
            plexUrl = localStorage.plexUrl;
            $('#plexUrl').val(localStorage.plexUrl);
            validateEnableConnectBtn('plexUrl');
            $('#forgetDivider, #forgetDetailsSection').show();
        }
        if (localStorage.plexToken && localStorage.plexToken !== "") {
            plexToken = localStorage.plexToken;
            $('#plexToken').val(localStorage.plexToken);
            validateEnableConnectBtn('plexToken');
            $('#forgetDivider, #forgetDetailsSection').show();
        }

        // Display a PIN code for that authentication as well
        $.ajax({
            "url": `https://plex.tv/pins.xml`,
            "headers": {
                "X-Plex-Client-Identifier": clientIdentifier,
                "X-Plex-Product": plexProduct,
                "X-Plex-Version": pastaVersion,
                "X-Plex-Platform": pastaPlatform,
                "X-Plex-Platform-Version": pastaPlatformVersion,
                "X-Plex-Device": deviceInfo,
                "X-Plex-Device-Name": deviceName
            },
            "method": "POST",
            "success": (data) => {
                let pinId = $(data).find('id')[0].innerHTML;
                let pinCode = $(data).find('code')[0].innerHTML;
    
                $('#pin-code-holder').html(pinCode);
                backOffTimer = Date.now();
                listenForValidPincode(pinId);
            },
            "error": (data) => {
                console.log("ERROR L121");
                console.log(data);
            }
        });
    } else {
        $('#new-pin-container').hide();
        $('#authed-pin-container').show();
        // We are using Pin Auth
        clientIdentifier = localStorage.clientIdentifier;
        plexToken = localStorage.pinAuthToken;
        getServers();
    }
});

function toggleAuthPages(value) {
    if (value == 'showPinControls') {
        $('#pin-auth-over-container').show();
        $('#url-auth-over-container').hide();
    } else {
        $('#pin-auth-over-container').hide();
        $('#url-auth-over-container').show();

        if (localStorage.isPinAuth) {
            $("#authWarningText").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> You are currently signed in via PIN. Please <a href="javascript:void(0)" onclick="forgetPinDetails()">sign out of PIN</a> before proceeding to connect using a URL / IP address.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
        }
    }
}

function listenForValidPincode (pinId) {
    let currentTime = Date.now();
    if ((currentTime - backOffTimer)/1000 < 180) {
        $.ajax({
            "url": `https://plex.tv/pins/${pinId}`,
            "headers": {
                "X-Plex-Client-Identifier": clientIdentifier,
                "X-Plex-Product": plexProduct,
                "X-Plex-Version": pastaVersion,
                "X-Plex-Platform": pastaPlatform,
                "X-Plex-Platform-Version": pastaPlatformVersion,
                "X-Plex-Device": deviceInfo,
                "X-Plex-Device-Name": deviceName
            },
            "method": "GET",
            "success": (data) => {
                if (data.pin.auth_token != null) {
                    plexToken = data.pin.auth_token;
                    // Save to local storage
                    localStorage.isPinAuth = true;
                    localStorage.pinAuthToken = plexToken;
                    localStorage.clientIdentifier = clientIdentifier;
                    $('#new-pin-container').hide();
                    $('#authed-pin-container').show();
                    getServers();
                } else {
                    setTimeout(() => {
                        listenForValidPincode(pinId);
                    }, 5000);
                }
            },
            "error": (data) => {
                console.log("ERROR L186");
                console.log(data);
                return;
            }
        });
    } else {
        $('#new-pin-container').html(' <p><i class="far fa-times-circle mr-2" style="color: #e5a00d; font-size: 1.5em; vertical-align: middle;"></i>PIN entry timed out. \
        Please <a href="javascript:void(0)" onclick="window.location.reload()">refresh the page</a> to get a new PIN.</p>');
    }
}

function getServers () {
    $.ajax({
        "url": `https://plex.tv/pms/servers.xml?X-Plex-Client-Identifier=${clientIdentifier}`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken
        },
        "success": (data) => {
            let servers = $(data).find('Server');
            if (servers.length > 1) {
                displayServers(servers);
                // Add server info to the list
                for (let i = 0; i < servers.length; i++) {
                    serverList.push({
                        name: $(servers[i]).attr("name"),
                        accessToken: $(servers[i]).attr("accessToken"),
                        address: $(servers[i]).attr("address"),
                        port: $(servers[i]).attr("port")
                    });
                }
            } else {
                plexToken = $(servers[0]).attr("accessToken");
                plexUrl = `http://${$(servers[0]).attr("address")}:${$(servers[0]).attr("port")}`;
                connectToPlex();
            }
        },
        "error": (data) => {
            console.log("ERROR L224");
            console.log(data);
            if (data.status == 401) {
                console.log("Unauthorized");
                $("#pinAuthWarning").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> Unauthorized (401) - It looks like the old PIN code is no longer valid. Please choose the "Click here to logout" above to authorise again.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
            }
        }
    });
}

function displayServers(servers) {
    $("#serverTable tbody").empty();
    $("#libraryTable tbody").empty();
    $("#tvShowsTable tbody").empty();
    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    for (let i = 0; i < servers.length; i++) {
        let rowHTML = `<tr onclick="chooseServer(${i}, this)">
                        <td>${$(servers[i]).attr("name")}</td>
                    </tr>`;
        $("#serverTable tbody").append(rowHTML);
    }
    $("#serverTableContainer").show();
}

function chooseServer(number, row) {
    $("#libraryTable tbody").empty();
    $("#tvShowsTable tbody").empty();
    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    $(row).siblings().removeClass("table-active");
    $(row).addClass("table-active");

    plexToken = serverList[number].accessToken;
    plexUrl = `http://${serverList[number].address}:${serverList[number].port}`;
    connectToPlex();
}

function validateEnableConnectBtn(context) {
    // Apply validation highlighting to URL field
    if (context == 'plexUrl') {
        if ($('#plexUrl').val() != "") {
            $('#plexUrl').removeClass("is-invalid").addClass("is-valid");
        }
        else {
            $('#plexUrl').removeClass("is-valid").addClass("is-invalid");
        }
    }
    else {
        // Apply validation highlighting to Plex Token field
        if ($('#plexToken').val() != "") {
            $('#plexToken').removeClass("is-invalid").addClass("is-valid");
        }
        else {
            $('#plexToken').removeClass("is-valid").addClass("is-invalid");
        }
    }

    // Enable or disable the button, depending on field status
    if (($('#plexUrl').val() != "") && ($('#plexToken').val() != "")) {
        $("#btnConnectToPlex").prop("disabled", false);
    }
    else {
        $("#btnConnectToPlex").prop("disabled", true);
    }
}

function forgetDetails() {
    localStorage.removeItem('plexUrl');
    localStorage.removeItem('plexToken');
    $('#plexUrl, #plexToken').val('').removeClass('is-valid is-invalid');
    $('#confirmForget').fadeIn(250).delay(750).fadeOut(1250, () => {
        $('#forgetDivider, #forgetDetailsSection').hide();
    });
}

function forgetPinDetails() {
    localStorage.removeItem('isPinAuth');
    localStorage.removeItem('pinAuthToken');
    localStorage.removeItem('clientIdentifier');
    window.location.reload();
}

function hideAlertForever() {
    $("#insecureWarning").hide();
    localStorage.showHttpAlert = 'false';
}

function connectToPlex() {
    plexUrl = plexUrl || $("#plexUrl").val().trim().replace(/\/+$/, '');
    plexToken = plexToken || $("#plexToken").val().trim();

    if (plexUrl.toLowerCase().indexOf("http") < 0) {
        plexUrl = `http://${plexUrl}`
    }

    $.ajax({
        "url": `${plexUrl}/library/sections/`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => {
            $("#authWarningText").empty();
            if ($('#rememberDetails').prop('checked')) {
                localStorage.plexUrl = plexUrl;
                localStorage.plexToken = plexToken;
                $('#forgetDivider, #forgetDetailsSection').show();
            }
            displayLibraries(data);
        },
        "error": (data) => {
            if (data.status == 401) {
                console.log("Unauthorized");
                $("#authWarningText").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> Unauthorized (401) - Please check that your X-Plex-Token is correct, and you are trying to connect to the correct Plex server.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
            }
            else if ((location.protocol == 'https:') && (localStorage.isPinAuth) && (plexUrl.indexOf('http:') > -1)) {
                console.log("Trying to use http over a https site with PIN authentication");
                $("#pinAuthWarning").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> Error - You are trying to access a http server via the site in https. If you cannot see your libraries below, please load this site \
                        over http by <a href="http://www.pastatool.com">clicking here</a>.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
            }
            else if ((location.protocol == 'https:') && (plexUrl.indexOf('http:') > -1)) {
                console.log("Trying to use http over a https site");
                $("#authWarningText").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> Error - You are trying to access a http server via the site in https. Please access your server via https, or load this site \
                        over http by <a href="http://www.pastatool.com">clicking here</a>.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
            }
            else {
                console.log("Unknown error, most likely bad URL / IP");
                $("#authWarningText").html(`<div class="alert alert-warning alert-dismissible fade show mt-3" role="alert">
                        <strong>Warning:</strong> Unknown Error (0) - This is usually caused by a wrong URL. Please verify the URL and try again.
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>`);
            }
            $("#libraryTable tbody").empty();
            $("#tvShowsTable tbody").empty();
            $("#seasonsTable tbody").empty();
            $("#episodesTable tbody").empty();
            $("#audioTable tbody").empty();
            $("#subtitleTable tbody").empty();
        }
    });
}

function displayLibraries(data) {
    const libraries = data.MediaContainer.Directory;

    $("#libraryTable tbody").empty();
    $("#tvShowsTable tbody").empty();
    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    for (let i = 0; i < libraries.length; i++) {
        let rowHTML = `<tr onclick="getAlphabet(${libraries[i].key}, this)">
                        <td>${libraries[i].title}</td>
                    </tr>`;
        $("#libraryTable tbody").append(rowHTML);
    }
}

function getAlphabet(uid, row) {
    $.ajax({
        "url": `${plexUrl}/library/sections/${uid}/firstCharacter`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => {
            libraryNumber = uid;
            displayAlphabet(data, row);
            $('#series-tab').tab('show');
        },
        "error": (data) => {
            console.log("ERROR L428");
            console.log(data);
        }
    });
}

function displayAlphabet(data, row) {
    const availableAlphabet = data.MediaContainer.Directory;

    $("#tvShowsTable tbody").empty();
    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    $(row).siblings().removeClass("table-active");
    $(row).addClass("table-active");
    $('#alphabetGroup').children().removeClass("btn-dark").addClass("btn-outline-dark").prop("disabled", true);

    for (let i = 0; i < availableAlphabet.length; i++) {
        if (availableAlphabet[i].title == "#") {
            $(`#btnHash`).prop("disabled", false);
        }
        else {
            $(`#btn${availableAlphabet[i].title}`).prop("disabled", false);
        }
    }
}

function getLibraryByLetter(element) {
    let letter = $(element).text();
    if (letter == "#") letter = "%23";

    $(element).siblings().removeClass("btn-dark").addClass("btn-outline-dark");
    $(element).removeClass("btn-outline-dark").addClass("btn-dark");

    $.ajax({
        "url": `${plexUrl}/library/sections/${libraryNumber}/firstCharacter/${letter}`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => displayTitles(data),
        "error": (data) => {
            console.log("ERROR L473");
            console.log(data);
        }
    });
}

function displayTitles(titles) {
    const tvShows = titles.MediaContainer.Metadata;
    $("#tvShowsTable tbody").empty();
    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    for (let i = 0; i < tvShows.length; i++) {
        let rowHTML = `<tr onclick="getTitleInfo(${tvShows[i].ratingKey}, this)">
                        <td>${tvShows[i].title}</td>
                        <td>${tvShows[i].year}</td>
                    </tr>`;
        $("#tvShowsTable tbody").append(rowHTML);
    }
}

function getTitleInfo(uid, row) {
    showId = uid;
    $.ajax({
        "url": `${plexUrl}/library/metadata/${uid}/children`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => {
            showTitleInfo(data, row);
            $('#episodes-tab').tab('show');
        },
        "error": (data) => {
            console.log("ERROR L510");
            console.log(data);
            if (data.status == 400) {
                // This is a "bad request" - this usually means a Movie was selected
                $('#progressModal #progressModalTitle').empty();
                $('#progressModal #progressModalTitle').text(`Invalid TV Show`);
                $('#progressModal #modalBodyText').empty();
                $('#progressModal #modalBodyText').append(`<div class="alert alert-warning mb-0" role="alert">
                        <div class="d-flex align-items-center">
                            This does not appear to be a valid TV Series, or this TV Series does not have any seasons associated with it.<br>
                            Please choose a valid TV Series; update the TV Series to have at least 1 Season; or go back and choose the proper library for TV Series.
                        </div>
                    </div>`);
                $('#progressModal').modal();
            }
        }
    });
}

function showTitleInfo(data, row) {
    const seasons = data.MediaContainer.Metadata;
    seasonsList.length = 0;

    $(row).siblings().removeClass("table-active");
    $(row).addClass("table-active");

    $("#seasonsTable tbody").empty();
    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    for (let i = 0; i < seasons.length; i++) {
        seasonsList.push(seasons[i].ratingKey);
        let rowHTML = `<tr onclick="getSeasonInfo(${seasons[i].ratingKey}, this)">
                        <td>${seasons[i].title}</td>
                    </tr>`;
        $("#seasonsTable tbody").append(rowHTML);
    }
}

function getSeasonInfo(uid, row) {
    seasonId = uid;
    $.ajax({
        "url": `${plexUrl}/library/metadata/${uid}/children`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => showSeasonInfo(data, row),
        "error": (data) => {
            console.log("ERROR L561");
            console.log(data);
        }
    });
}

function showSeasonInfo(data, row) {
    const episodes = data.MediaContainer.Metadata;

    $(row).siblings().removeClass("table-active");
    $(row).addClass("table-active");

    $("#episodesTable tbody").empty();
    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    for (let i = 0; i < episodes.length; i++) {
        let rowHTML = `<tr onclick="getEpisodeInfo(${episodes[i].ratingKey}, this)">
                        <td>${episodes[i].title}</td>
                    </tr>`;
        $("#episodesTable tbody").append(rowHTML);
    }
}

function getEpisodeInfo(uid, row) {
    episodeId = uid;
    $.ajax({
        "url": `${plexUrl}/library/metadata/${uid}`,
        "method": "GET",
        "headers": {
            "X-Plex-Token": plexToken,
            "Accept": "application/json"
        },
        "success": (data) => showEpisodeInfo(data, row),
        "error": (data) => {
            console.log("ERROR L596");
            console.log(data);
        }
    });
}

function showEpisodeInfo(data, row) {
    const streams = data.MediaContainer.Metadata[0].Media[0].Part[0].Stream;
    const partId = data.MediaContainer.Metadata[0].Media[0].Part[0].id;

    $(row).siblings().removeClass("table-active");
    $(row).addClass("table-active");

    $("#audioTable tbody").empty();
    $("#subtitleTable tbody").empty();

    // We need to keep track if any subtitles are selected - if not, then we need to make the subtitle row table-active
    let subtitlesChosen = false;

    for (let i = 0; i < streams.length; i++) {
        if (streams[i].streamType == 2) {
            let rowHTML = `<tr ${streams[i].selected ? "class='table-active'" : ""} onclick="setAudioStream(${partId}, ${streams[i].id}, this)">
                        <td class="name">${streams[i].displayTitle}</td>
                        <td class="title">${streams[i].title}</td>
                        <td class="language">${streams[i].language}</td>
                        <td class="code">${streams[i].languageCode}</td>
                    </tr>`;
            $("#audioTable tbody").append(rowHTML);
        }
        else if (streams[i].streamType == 3) {
            if (streams[i].selected) subtitlesChosen = true;
            let rowHTML = `<tr ${streams[i].selected ? "class='table-active'" : ""} onclick="setSubtitleStream(${partId}, ${streams[i].id}, this)">
                        <td class="name">${streams[i].displayTitle}</td>
                        <td class="title">${streams[i].title}</td>
                        <td class="language">${streams[i].language}</td>
                        <td class="code">${streams[i].languageCode}</td>
                    </tr>`;
            $("#subtitleTable tbody").append(rowHTML);
        }
    }

    // Append the "No Subtitles" row to the top of the tracks table
    let noSubsRow = `<tr ${subtitlesChosen ? "" : "class='table-active'"} onclick="setSubtitleStream(${partId}, 0, this)">
                        <td class="name">No Subtitles</td>
                        <td class="title">--</td>
                        <td class="language">--</td>
                        <td class="code">--</td>
                    </tr>`;
    $("#subtitleTable tbody").prepend(noSubsRow);
}

async function setAudioStream(partsId, streamId, row) {
    let singleEpisode = $("#singleEpisode").prop("checked");
    let singleSeason = $("#singleSeason").prop("checked");
    // Need these 2 variables and function for progress bar
    let currentProgress = 0;
    let maxProgress = 0;

    if (singleEpisode) {
        $.ajax({
            "url": `${plexUrl}/library/parts/${partsId}?audioStreamID=${streamId}&allParts=1`,
            "method": "POST",
            "headers": {
                "X-Plex-Token": plexToken,
                "Accept": "application/json"
            },
            "success": (data) => {
                $(row).siblings().removeClass("table-active");
                $(row).addClass("table-active").addClass("success-transition");
                setTimeout(() => {
                    $(row).removeClass('success-transition');
                }, 1750);
            },
            "error": (data) => {
                console.log("ERROR L670");
                console.log(data);
            }
        });
    }
    else {
        // Show the modal to set progress
        $('#progressModal #progressModalTitle').empty();
        $('#progressModal #progressModalTitle').text(`Processing Audio Changes`);
        $('#progressModal #modalBodyText').empty();
        $('#progressModal #modalBodyText').append(`<div class="alert alert-warning" role="alert">
                <div class="d-flex align-items-center">
                    <span id="modalTitleText">Please do not close this tab or refresh until the process is complete</span>
            </div>
            <div class="progress" id="progressBarContainer">
                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-warning" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>`);
        $('#progressModal').modal();

        let promiseConstructors = []; // This will hold the details that will then be added to the full promises in matchPromises
        let matchPromises = []; // This will store the promises to change the audio for given files. It means we can run in parallel and await them all
        let searchTitle = ($(".title", row).text() == "undefined") ? undefined : $(".title", row).text();
        let searchName = ($(".name", row).text() == "undefined") ? undefined : $(".name", row).text();
        let searchLanguage = ($(".language", row).text() == "undefined") ? undefined : $(".language", row).text();
        let searchCode = ($(".code", row).text() == "undefined") ? undefined : $(".code", row).text();

        // We have the Seasons Ids stored in seasonsList, so iterate over them to get all the episodes
        let episodeList = [];
        if (singleSeason) {
            // If the "Single Season" button is selected, we only want to change the current season's episodes
            let seasonEpisodes = await $.ajax({
                "url": `${plexUrl}/library/metadata/${seasonId}/children`,
                "method": "GET",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            });
            for (let k = 0; k < seasonEpisodes.MediaContainer.Metadata.length; k++) {
                episodeList.push(seasonEpisodes.MediaContainer.Metadata[k].ratingKey);
            }
        } else {
            // Else we want to get all the episodes from every season
            for (let i = 0; i < seasonsList.length; i++) {
                let seasonEpisodes = await $.ajax({
                    "url": `${plexUrl}/library/metadata/${seasonsList[i]}/children`,
                    "method": "GET",
                    "headers": {
                        "X-Plex-Token": plexToken,
                        "Accept": "application/json"
                    }
                });
                for (let j = 0; j < seasonEpisodes.MediaContainer.Metadata.length; j++) {
                    episodeList.push(seasonEpisodes.MediaContainer.Metadata[j].ratingKey);
                }
            }
        }

        // Set the progress bar to have a certain length
        maxProgress = episodeList.length;
        $('#progressBar').attr('aria-valuemax', maxProgress);
        // We have the episodes in episodeList, now we need to go through each one and see what streams are available
        for (let i = 0; i < episodeList.length; i++) {
            // Update the progressbar
            currentProgress++;
            const calculatedWidth = (currentProgress / maxProgress) * 100;
            $('#progressBar').width(`${calculatedWidth}%`);
            $('#progressBar').attr('aria-valuenow', currentProgress);

            let episodeData = await $.ajax({
                "url": `${plexUrl}/library/metadata/${episodeList[i]}`,
                "method": "GET",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            });
            const seasonNumber = episodeData.MediaContainer.Metadata[0].parentIndex;
            const episodeNumber = episodeData.MediaContainer.Metadata[0].index;
            const episodePartId = episodeData.MediaContainer.Metadata[0].Media[0].Part[0].id;
            const episodeStreams = episodeData.MediaContainer.Metadata[0].Media[0].Part[0].Stream;

            // Loop through each audio stream and check for any matches using the searchTitle, searchName, searchLanguage, searchCode
            let hasMatch = false;
            let matchType = "";
            let potentialMatches = [];
            let selectedTrack = {
                "matchId": "",
                "matchLevel": 0,
                "matchName": ""
            };
            let bestMatch;

            for (let j = 0; j < episodeStreams.length; j++) {
                // Audio streams are streamType 2, so we only care about that
                if (episodeStreams[j].streamType == "2") {
                    // If EVERYTHING is a match, even if they are "undefined" then select it
                    if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].language == searchLanguage) && (episodeStreams[j].languageCode == searchCode)) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 6;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 6,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                    // If the displayTitle and title are the same, we have an instant match (also rule out any undefined matches)
                    else if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].title != "undefined") && (episodeStreams[j].displayTitle != "undefined")) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 5;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 5,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                    // If the titles are the same (rule out undefined match)
                    else if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].title != "undefined")) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 4;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 4,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                    // If the names are the same (rule out undefined match)
                    else if ((episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].displayTitle != "undefined")) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 3;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 3,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                    // If the languages are the same (rule out undefined match)
                    else if ((episodeStreams[j].language == searchLanguage) && (episodeStreams[j].language != "undefined")) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 2;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 2,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                    // If the language codes are the same (rule out undefined match)
                    else if ((episodeStreams[j].languageCode == searchCode) && (episodeStreams[j].languageCode != "undefined")) {
                        if (episodeStreams[j].selected == true) {
                            selectedTrack.matchId = episodeStreams[j].id;
                            selectedTrack.matchLevel = 1;
                            selectedTrack.matchName = episodeStreams[j].displayTitle;
                        }
                        else {
                            potentialMatches.push({
                                "matchId": episodeStreams[j].id,
                                "matchLevel": 1,
                                "matchName": episodeStreams[j].displayTitle
                            });
                        }
                    }
                }
            }

            // If there are no potential matches, then return hasMatch = false so we can skip sending unnecessary commands to plex
            if (potentialMatches.length == 0) {
                hasMatch = false;
            }
            else {
                // If there are potential matches - get the highest matchLevel (most accurate) and compare it to the currently selected track
                bestMatch = potentialMatches.reduce((p, c) => p.matchLevel > c.matchLevel ? p : c);
                if (bestMatch.matchLevel > selectedTrack.matchLevel) {
                    // By default selectedTrack.matchLevel = 0, so even if there is no selected track, this comparison will work
                    hasMatch = true;
                    if (bestMatch.matchLevel == 6) matchType = "Everything";
                    else if (bestMatch.matchLevel == 5) matchType = "Name and Title";
                    else if (bestMatch.matchLevel == 4) matchType = "Title";
                    else if (bestMatch.matchLevel == 3) matchType = "Name";
                    else if (bestMatch.matchLevel == 2) matchType = "Language";
                    else if (bestMatch.matchLevel == 1) matchType = "Language Code";
                }
                else {
                    hasMatch = false;
                }
            }

            if (hasMatch) {
                // There is a match, so update the audio track using the newStreamId and episodePartId
                promiseConstructors.push({
                    "url": `${plexUrl}/library/parts/${episodePartId}?audioStreamID=${bestMatch.matchId}&allParts=1`,
                    "messageAppend": `<span><strong>S${seasonNumber}E${episodeNumber} - ${episodeData.MediaContainer.Metadata[0].title}</strong> updated with Audio Track: <strong>${bestMatch.matchName}</strong> because of a match on <strong>${matchType}</strong></span><br />`
                });
            }
            else {
                //console.log(`Episode: ${episodeData.MediaContainer.Metadata[0].title} has no match, or there is only 1 audio track`);
            }
        }

        // Reset the progress bar and modal text
        $("#modalBodyText #modalTitleText").text("Updating matches... Please do not close this tab or refresh until the process is complete.");
        maxProgress = promiseConstructors.length;
        $('#progressBar').attr('aria-valuemax', maxProgress);
        $('#progressBar').attr('aria-valuenow', 0);

        function futurePromise(data) {
            return axios({
                "url": data.url,
                "method": "POST",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            }).then((result) => {
                $('#progressModal #modalBodyText').append(data.messageAppend);
                $(row).siblings().removeClass("table-active");
                $(row).addClass("table-active");
                handleProgress();
            }).catch((e) => console.log(e));
        }

        for (let k = 0; k < promiseConstructors.length; k++) {
            let axiosPromise = futurePromise(promiseConstructors[k]);
            matchPromises.push(axiosPromise);
        }

        function handleProgress() {
            currentProgress++;
            const calculatedWidth = (currentProgress / maxProgress) * 100;
            $('#progressBar').width(`${calculatedWidth}%`);
            $('#progressBar').attr('aria-valuenow', currentProgress);
        };

        try {
            Promise.allSettled(matchPromises).then(() => {
                $('#modalBodyText .alert').removeClass("alert-warning").addClass("alert-success");
                $("#modalBodyText #modalTitleText").text("Processing Complete! You can now close this popup.");
                $('#modalBodyText #progressBarContainer').hide();
            });
        }
        catch (e) {
            console.log("ERROR L936");
            console.log(e);
        }
    }
}

async function setSubtitleStream(partsId, streamId, row) {
    let singleEpisode = $("#singleEpisode").prop("checked");
    let singleSeason = $("#singleSeason").prop("checked");
    // Need these 2 variables and function for progress bar
    let currentProgress = 0;
    let maxProgress = 0;

    if (singleEpisode) {
        $.ajax({
            "url": `${plexUrl}/library/parts/${partsId}?subtitleStreamID=${streamId}&allParts=1`,
            "method": "POST",
            "headers": {
                "X-Plex-Token": plexToken,
                "Accept": "application/json"
            },
            "success": (data) => {
                $(row).siblings().removeClass("table-active");
                $(row).addClass("table-active").addClass("success-transition");
                setTimeout(() => {
                    $(row).removeClass('success-transition');
                }, 1750);
            },
            "error": (data) => {
                console.log("ERROR L965");
                console.log(data);
            }
        });
    }
    else {
        // Show the modal to set progress
        $('#progressModal #progressModalTitle').empty();
        $('#progressModal #progressModalTitle').text(`Processing Subtitle Changes`);
        $('#progressModal #modalBodyText').empty();
        $('#progressModal #modalBodyText').append(`<div class="alert alert-warning" role="alert">
                <div class="d-flex align-items-center">
                    <span id="modalTitleText">Processing Episodes... Please do not close this tab or refresh until the process is complete.</span>
            </div>
            <div class="progress mt-2" id="progressBarContainer">
                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-warning" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div>`);
        $('#progressModal').modal();

        let promiseConstructors = []; // This will hold the details that will then be added to the full promises in matchPromises
        let matchPromises = []; // This will store the promises to change the audio for given files. It means we can run in parallel and await them all
        let searchTitle = ($(".title", row).text() == "undefined") ? undefined : $(".title", row).text();
        let searchName = ($(".name", row).text() == "undefined") ? undefined : $(".name", row).text();
        let searchLanguage = ($(".language", row).text() == "undefined") ? undefined : $(".language", row).text();
        let searchCode = ($(".code", row).text() == "undefined") ? undefined : $(".code", row).text();

        // We have the Seasons Ids stored in seasonsList, so iterate over them to get all the episodes
        let episodeList = [];
        if (singleSeason) {
            // If the "Single Season" button is selected, we only want to change the current season's episodes
            let seasonEpisodes = await $.ajax({
                "url": `${plexUrl}/library/metadata/${seasonId}/children`,
                "method": "GET",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            });
            for (let k = 0; k < seasonEpisodes.MediaContainer.Metadata.length; k++) {
                episodeList.push(seasonEpisodes.MediaContainer.Metadata[k].ratingKey);
            }
        } else {
            // Else we want to get all the episodes from every season
            for (let i = 0; i < seasonsList.length; i++) {
                let seasonEpisodes = await $.ajax({
                    "url": `${plexUrl}/library/metadata/${seasonsList[i]}/children`,
                    "method": "GET",
                    "headers": {
                        "X-Plex-Token": plexToken,
                        "Accept": "application/json"
                    }
                });
                for (let j = 0; j < seasonEpisodes.MediaContainer.Metadata.length; j++) {
                    episodeList.push(seasonEpisodes.MediaContainer.Metadata[j].ratingKey);
                }
            }
        }

        // Set the progress bar to have a certain length
        maxProgress = episodeList.length;
        $('#progressBar').attr('aria-valuemax', maxProgress);
        // We have the episodes in episodeList, now we need to go through each one and see what streams are available
        for (let i = 0; i < episodeList.length; i++) {
            // Update the progressbar
            currentProgress++;
            const calculatedWidth = (currentProgress / maxProgress) * 100;
            $('#progressBar').width(`${calculatedWidth}%`);
            $('#progressBar').attr('aria-valuenow', currentProgress);

            let episodeData = await $.ajax({
                "url": `${plexUrl}/library/metadata/${episodeList[i]}`,
                "method": "GET",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            });
            const seasonNumber = episodeData.MediaContainer.Metadata[0].parentIndex;
            const episodeNumber = episodeData.MediaContainer.Metadata[0].index;
            const episodePartId = episodeData.MediaContainer.Metadata[0].Media[0].Part[0].id;
            const episodeStreams = episodeData.MediaContainer.Metadata[0].Media[0].Part[0].Stream;

            // If streamId = 0 then we are unsetting the subtitles. Otherwise we need to find the best matches for each episode
            if (streamId != 0) {
                // Loop through each subtitle stream and check for any matches using the searchTitle, searchName, searchLanguage, searchCode
                let hasMatch = false;
                let matchType = "";
                let potentialMatches = [];
                let selectedTrack = {
                    "matchId": "",
                    "matchLevel": 0,
                    "matchName": ""
                };
                let bestMatch;

                for (let j = 0; j < episodeStreams.length; j++) {
                    // Subtitle streams are streamType 3, so we only care about that
                    if (episodeStreams[j].streamType == "3") {
                        // If EVERYTHING is a match, even if they are "undefined" then select it
                        if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].language == searchLanguage) && (episodeStreams[j].languageCode == searchCode)) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 6;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 6,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                        // If the displayTitle and title are the same, we have an instant match (also rule out any undefined matches)
                        else if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].title != "undefined") && (episodeStreams[j].displayTitle != "undefined")) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 5;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 5,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                        // If the titles are the same (rule out undefined match)
                        else if ((episodeStreams[j].title == searchTitle) && (episodeStreams[j].title != "undefined")) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 4;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 4,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                        // If the names are the same (rule out undefined match)
                        else if ((episodeStreams[j].displayTitle == searchName) && (episodeStreams[j].displayTitle != "undefined")) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 3;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 3,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                        // If the languages are the same (rule out undefined match)
                        else if ((episodeStreams[j].language == searchLanguage) && (episodeStreams[j].language != "undefined")) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 2;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 2,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                        // If the language codes are the same (rule out undefined match)
                        else if ((episodeStreams[j].languageCode == searchCode) && (episodeStreams[j].languageCode != "undefined")) {
                            if (episodeStreams[j].selected == true) {
                                selectedTrack.matchId = episodeStreams[j].id;
                                selectedTrack.matchLevel = 1;
                                selectedTrack.matchName = episodeStreams[j].displayTitle;
                            }
                            else {
                                potentialMatches.push({
                                    "matchId": episodeStreams[j].id,
                                    "matchLevel": 1,
                                    "matchName": episodeStreams[j].displayTitle
                                });
                            }
                        }
                    }
                }

                // If there are no potential matches, then return hasMatch = false so we can skip sending unnecessary commands to plex
                if (potentialMatches.length == 0) {
                    hasMatch = false;
                }
                else {
                    // If there are potential matches - get the highest matchLevel (most accurate) and compare it to the currently selected track
                    bestMatch = potentialMatches.reduce((p, c) => p.matchLevel > c.matchLevel ? p : c);
                    if (bestMatch.matchLevel > selectedTrack.matchLevel) {
                        // By default selectedTrack.matchLevel = 0, so even if there is no selected track, this comparison will work
                        hasMatch = true;
                        if (bestMatch.matchLevel == 6) matchType = "Everything";
                        else if (bestMatch.matchLevel == 5) matchType = "Name and Title";
                        else if (bestMatch.matchLevel == 4) matchType = "Title";
                        else if (bestMatch.matchLevel == 3) matchType = "Name";
                        else if (bestMatch.matchLevel == 2) matchType = "Language";
                        else if (bestMatch.matchLevel == 1) matchType = "Language Code";
                    }
                    else {
                        hasMatch = false;
                    }
                }

                if (hasMatch) {
                    // There is a match, so update the subtitle track using the currentMatch.matchId and episodePartId
                    promiseConstructors.push({
                        "url": `${plexUrl}/library/parts/${episodePartId}?subtitleStreamID=${bestMatch.matchId}&allParts=1`,
                        "messageAppend": `<span><strong>S${seasonNumber}E${episodeNumber} - ${episodeData.MediaContainer.Metadata[0].title}</strong> updated with Subtitle Track: <strong>${bestMatch.matchName}</strong> because of a match on <strong>${matchType}</strong></span><br />`
                    });
                }
                else {
                    //console.log(`Episode: ${episodeData.MediaContainer.Metadata[0].title} has no match, or there is only 1 subtitle track`);
                }
            }
            else {
                // streamId = 0, which means we just want to set the subtitleStreamID = 0 for every episode
                promiseConstructors.push({
                    "url": `${plexUrl}/library/parts/${episodePartId}?subtitleStreamID=0&allParts=1`,
                    "messageAppend": `<span><strong>S${seasonNumber}E${episodeNumber} - ${episodeData.MediaContainer.Metadata[0].title}</strong> has had the subtitles <strong>deselected</strong></span><br />`
                });
            }
        }

        // Reset the progress bar and modal text
        $("#modalBodyText #modalTitleText").text("Updating matches... Please do not close this tab or refresh until the process is complete.");
        maxProgress = promiseConstructors.length;
        $('#progressBar').attr('aria-valuemax', maxProgress);
        $('#progressBar').attr('aria-valuenow', 0);

        function futurePromise(data) {
            return axios({
                "url": data.url,
                "method": "POST",
                "headers": {
                    "X-Plex-Token": plexToken,
                    "Accept": "application/json"
                }
            }).then((result) => {
                $('#progressModal #modalBodyText').append(data.messageAppend);
                $(row).siblings().removeClass("table-active");
                $(row).addClass("table-active");
                handleProgress();
            }).catch((e) => console.log(e));
        } 

        for (let k = 0; k < promiseConstructors.length; k++) {
            let axiosPromise = futurePromise(promiseConstructors[k]);
            matchPromises.push(axiosPromise);
        }

        function handleProgress() {
            currentProgress++;
            const calculatedWidth = (currentProgress / maxProgress) * 100;
            $('#progressBar').width(`${calculatedWidth}%`);
            $('#progressBar').attr('aria-valuenow', currentProgress);
        };

        try {
            Promise.allSettled(matchPromises).then(() => {
                $('#modalBodyText .alert').removeClass("alert-warning").addClass("alert-success");
                $("#modalBodyText #modalTitleText").text("Processing Complete! You can now close this popup.");
                $('#modalBodyText #progressBarContainer').hide();
            });
        }
        catch (e) {
                console.log("ERROR L1241");
                console.log(e);
        }
    }
}