forked from FreeTubeApp/FreeTube
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-settings.js
More file actions
1265 lines (1110 loc) · 42.4 KB
/
data-settings.js
File metadata and controls
1265 lines (1110 loc) · 42.4 KB
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
import { defineComponent } from 'vue'
import FtSettingsSection from '../ft-settings-section/ft-settings-section.vue'
import { mapActions, mapMutations } from 'vuex'
import FtButton from '../ft-button/ft-button.vue'
import FtFlexBox from '../ft-flex-box/ft-flex-box.vue'
import FtPrompt from '../ft-prompt/ft-prompt.vue'
import FtToggleSwitch from '../ft-toggle-switch/ft-toggle-switch.vue'
import { MAIN_PROFILE_ID } from '../../../constants'
import { calculateColorLuminance, getRandomColor } from '../../helpers/colors'
import {
copyToClipboard,
deepCopy,
escapeHTML,
getTodayDateStrLocalTimezone,
readFileFromDialog,
showOpenDialog,
showSaveDialog,
showToast,
writeFileFromDialog,
} from '../../helpers/utils'
import { invidiousAPICall } from '../../helpers/api/invidious'
import { getLocalChannel } from '../../helpers/api/local'
export default defineComponent({
name: 'DataSettings',
components: {
'ft-settings-section': FtSettingsSection,
'ft-button': FtButton,
'ft-flex-box': FtFlexBox,
'ft-prompt': FtPrompt,
'ft-toggle-switch': FtToggleSwitch,
},
data: function () {
return {
showExportSubscriptionsPrompt: false,
subscriptionsPromptValues: [
'freetube',
'youtubenew',
'youtube',
'youtubeold',
'newpipe',
'close'
],
shouldExportPlaylistForOlderVersions: false,
}
},
computed: {
backendPreference: function () {
return this.$store.getters.getBackendPreference
},
backendFallback: function () {
return this.$store.getters.getBackendFallback
},
profileList: function () {
return this.$store.getters.getProfileList
},
allPlaylists: function () {
return this.$store.getters.getAllPlaylists
},
historyCacheSorted: function () {
return this.$store.getters.getHistoryCacheSorted
},
exportSubscriptionsPromptNames: function () {
const exportFreeTube = this.$t('Settings.Data Settings.Export FreeTube')
const exportYouTube = this.$t('Settings.Data Settings.Export YouTube')
const exportNewPipe = this.$t('Settings.Data Settings.Export NewPipe')
return [
`${exportFreeTube} (.db)`,
`${exportYouTube} (.csv)`,
`${exportYouTube} (.json)`,
`${exportYouTube} (.opml)`,
`${exportNewPipe} (.json)`,
this.$t('Close')
]
},
primaryProfile: function () {
return deepCopy(this.profileList[0])
}
},
methods: {
openProfileSettings: function () {
this.$router.push({
path: '/settings/profile/'
})
},
importSubscriptions: async function () {
const options = {
properties: ['openFile'],
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['db', 'csv', 'json', 'opml', 'xml']
}
]
}
const response = await showOpenDialog(options)
if (response.canceled || response.filePaths?.length === 0) {
return
}
let textDecode
try {
textDecode = await readFileFromDialog(response)
} catch (err) {
const message = this.$t('Settings.Data Settings.Unable to read file')
showToast(`${message}: ${err}`)
return
}
response.filePaths.forEach(filePath => {
if (filePath.endsWith('.csv')) {
this.importCsvYouTubeSubscriptions(textDecode)
} else if (filePath.endsWith('.db')) {
this.importFreeTubeSubscriptions(textDecode)
} else if (filePath.endsWith('.opml') || filePath.endsWith('.xml')) {
this.importOpmlYouTubeSubscriptions(textDecode)
} else if (filePath.endsWith('.json')) {
textDecode = JSON.parse(textDecode)
if (textDecode.subscriptions) {
this.importNewPipeSubscriptions(textDecode)
} else {
this.importYouTubeSubscriptions(textDecode)
}
}
})
},
importFreeTubeSubscriptions: function (textDecode) {
textDecode = textDecode.split('\n')
textDecode.pop()
textDecode = textDecode.map(data => JSON.parse(data))
const firstEntry = textDecode[0]
if (firstEntry.channelId && firstEntry.channelName && firstEntry.channelThumbnail && firstEntry._id && firstEntry.profile) {
// Old FreeTube subscriptions format detected, so convert it to the new one:
textDecode = this.convertOldFreeTubeFormatToNew(textDecode)
}
const requiredKeys = [
'_id',
'name',
'bgColor',
'textColor',
'subscriptions'
]
textDecode.forEach((profileData) => {
// We would technically already be done by the time the data is parsed,
// however we want to limit the possibility of malicious data being sent
// to the app, so we'll only grab the data we need here.
const profileObject = {}
Object.keys(profileData).forEach((key) => {
if (!requiredKeys.includes(key)) {
const message = this.$t('Settings.Data Settings.Unknown data key')
showToast(`${message}: ${key}`)
} else {
profileObject[key] = profileData[key]
}
})
if (Object.keys(profileObject).length < requiredKeys.length) {
const message = this.$t('Settings.Data Settings.Profile object has insufficient data, skipping item')
showToast(message)
} else {
if (profileObject._id === MAIN_PROFILE_ID) {
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(profileObject.subscriptions)
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.filter((sub, index) => {
const profileIndex = this.primaryProfile.subscriptions.findIndex((x) => {
return x.name === sub.name
})
return profileIndex === index
})
this.updateProfile(this.primaryProfile)
} else {
const existingProfileIndex = this.profileList.findIndex((profile) => {
return profile.name.includes(profileObject.name)
})
if (existingProfileIndex !== -1) {
const existingProfile = deepCopy(this.profileList[existingProfileIndex])
existingProfile.subscriptions = existingProfile.subscriptions.concat(profileObject.subscriptions)
existingProfile.subscriptions = existingProfile.subscriptions.filter((sub, index) => {
const profileIndex = existingProfile.subscriptions.findIndex((x) => {
return x.name === sub.name
})
return profileIndex === index
})
this.updateProfile(existingProfile)
} else {
this.updateProfile(profileObject)
}
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(profileObject.subscriptions)
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.filter((sub, index) => {
const profileIndex = this.primaryProfile.subscriptions.findIndex((x) => {
return x.name === sub.name
})
return profileIndex === index
})
this.updateProfile(this.primaryProfile)
}
}
})
showToast(this.$t('Settings.Data Settings.All subscriptions and profiles have been successfully imported'))
},
importCsvYouTubeSubscriptions: async function(textDecode) { // first row = header, last row = empty
const youtubeSubscriptions = textDecode.split('\n').filter(sub => {
return sub !== ''
})
const subscriptions = []
const errorList = []
showToast(this.$t('Settings.Data Settings.This might take a while, please wait'))
this.updateShowProgressBar(true)
this.setProgressBarPercentage(0)
let count = 0
const splitCSVRegex = /(?:,|\n|^)("(?:(?:"")|[^"])*"|[^\n",]*|(?:\n|$))/g
const ytsubs = youtubeSubscriptions.slice(1).map(yt => {
return [...yt.matchAll(splitCSVRegex)].map(s => {
let newVal = s[1]
if (newVal.startsWith('"')) {
newVal = newVal.substring(1, newVal.length - 2).replaceAll('""', '"')
}
return newVal
})
}).filter(channel => {
return channel.length > 0
})
new Promise((resolve) => {
let finishCount = 0
ytsubs.forEach(async (yt) => {
const { subscription, result } = await this.subscribeToChannel({
channelId: yt[0],
subscriptions: subscriptions,
channelName: yt[2],
count: count++,
total: ytsubs.length
})
if (result === 1) {
subscriptions.push(subscription)
} else if (result === -1) {
errorList.push(yt)
}
finishCount++
if (finishCount === ytsubs.length) {
resolve(true)
}
})
}).then(_ => {
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(subscriptions)
this.updateProfile(this.primaryProfile)
if (errorList.length !== 0) {
errorList.forEach(e => { // log it to console for now, dedicated tab for 'error' channels needed
console.error(`failed to import ${e[2]}. Url to channel: ${e[1]}.`)
})
showToast(this.$t('Settings.Data Settings.One or more subscriptions were unable to be imported'))
} else {
showToast(this.$t('Settings.Data Settings.All subscriptions have been successfully imported'))
}
}).finally(_ => {
this.updateShowProgressBar(false)
})
},
importYouTubeSubscriptions: async function (textDecode) {
const subscriptions = []
const errorList = []
showToast(this.$t('Settings.Data Settings.This might take a while, please wait'))
this.updateShowProgressBar(true)
this.setProgressBarPercentage(0)
let count = 0
new Promise((resolve) => {
let finishCount = 0
textDecode.forEach(async (channel) => {
const snippet = channel.snippet
if (typeof snippet === 'undefined') {
const message = this.$t('Settings.Data Settings.Invalid subscriptions file')
showToast(message)
throw new Error('Unable to find channel data')
}
const { subscription, result } = await this.subscribeToChannel({
channelId: snippet.resourceId.channelId,
subscriptions: subscriptions,
channelName: snippet.title,
thumbnail: snippet.thumbnails.default.url,
count: count++,
total: textDecode.length
})
if (result === 1) {
subscriptions.push(subscription)
} else if (result === -1) {
errorList.push([snippet.resourceId.channelId, `https://www.youtube.com/channel/${snippet.resourceId.channelId}`, snippet.title])
}
finishCount++
if (finishCount === textDecode.length) {
resolve(true)
}
})
}).then(_ => {
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(subscriptions)
this.updateProfile(this.primaryProfile)
if (errorList.length !== 0) {
errorList.forEach(e => { // log it to console for now, dedicated tab for 'error' channels needed
console.error(`failed to import ${e[2]}. Url to channel: ${e[1]}.`)
})
showToast(this.$t('Settings.Data Settings.One or more subscriptions were unable to be imported'))
} else {
showToast(this.$t('Settings.Data Settings.All subscriptions have been successfully imported'))
}
}).finally(_ => {
this.updateShowProgressBar(false)
})
},
importOpmlYouTubeSubscriptions: async function (data) {
let xmlDom
const domParser = new DOMParser()
try {
xmlDom = domParser.parseFromString(data, 'application/xml')
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#error_handling
const errorNode = xmlDom.querySelector('parsererror')
if (errorNode) {
throw errorNode.textContent
}
} catch (err) {
console.error('error reading OPML subscriptions file, falling back to HTML parser...')
console.error(err)
// try parsing with the html parser instead which is more lenient
try {
const htmlDom = domParser.parseFromString(data, 'text/html')
xmlDom = htmlDom
} catch {
const message = this.$t('Settings.Data Settings.Invalid subscriptions file')
showToast(`${message}: ${err}`)
return
}
}
const feedData = xmlDom.querySelectorAll('body outline[xmlUrl]')
if (feedData.length === 0) {
const message = this.$t('Settings.Data Settings.Invalid subscriptions file')
showToast(message)
return
}
const subscriptions = []
showToast(this.$t('Settings.Data Settings.This might take a while, please wait'))
this.updateShowProgressBar(true)
this.setProgressBarPercentage(0)
let count = 0
feedData.forEach(async (channel) => {
const xmlUrl = channel.getAttribute('xmlUrl')
let channelId
if (xmlUrl.includes('https://www.youtube.com/feeds/videos.xml?channel_id=')) {
channelId = new URL(xmlUrl).searchParams.get('channel_id')
} else if (xmlUrl.includes('/feed/channel/')) {
// handle invidious exports https://yewtu.be/feed/channel/{CHANNELID}
channelId = new URL(xmlUrl).pathname.split('/').filter(part => part).at(-1)
} else {
console.error(`Unknown xmlUrl format: ${xmlUrl}`)
}
const subExists = this.primaryProfile.subscriptions.findIndex((sub) => {
return sub.id === channelId
})
if (subExists === -1) {
let channelInfo
if (this.backendPreference === 'invidious') {
channelInfo = await this.getChannelInfoInvidious(channelId)
} else {
channelInfo = await this.getChannelInfoLocal(channelId)
}
if (typeof channelInfo.author !== 'undefined') {
const subscription = {
id: channelId,
name: channelInfo.author,
thumbnail: channelInfo.authorThumbnails[1].url
}
subscriptions.push(subscription)
}
}
count++
const progressPercentage = (count / feedData.length) * 100
this.setProgressBarPercentage(progressPercentage)
if (count === feedData.length) {
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(subscriptions)
this.updateProfile(this.primaryProfile)
if (subscriptions.length < count) {
showToast(this.$t('Settings.Data Settings.One or more subscriptions were unable to be imported'))
} else {
showToast(this.$t('Settings.Data Settings.All subscriptions have been successfully imported'))
}
this.updateShowProgressBar(false)
}
})
},
importNewPipeSubscriptions: async function (newPipeData) {
if (typeof newPipeData.subscriptions === 'undefined') {
showToast(this.$t('Settings.Data Settings.Invalid subscriptions file'))
return
}
const newPipeSubscriptions = newPipeData.subscriptions.filter((channel, index) => {
return new URL(channel.url).hostname === 'www.youtube.com'
})
const subscriptions = []
const errorList = []
showToast(this.$t('Settings.Data Settings.This might take a while, please wait'))
this.updateShowProgressBar(true)
this.setProgressBarPercentage(0)
let count = 0
new Promise((resolve) => {
let finishCount = 0
newPipeSubscriptions.forEach(async (channel, index) => {
const channelId = channel.url.replace(/https:\/\/(www\.)?youtube\.com\/channel\//, '')
const { subscription, result } = await this.subscribeToChannel({
channelId: channelId,
subscriptions: subscriptions,
channelName: channel.name,
count: count++,
total: newPipeSubscriptions.length
})
if (result === 1) {
subscriptions.push(subscription)
}
if (result === -1) {
errorList.push([channelId, channel.url, channel.name])
}
finishCount++
if (finishCount === newPipeSubscriptions.length) {
resolve(true)
}
})
}).then(_ => {
this.primaryProfile.subscriptions = this.primaryProfile.subscriptions.concat(subscriptions)
this.updateProfile(this.primaryProfile)
if (errorList.count > 0) {
errorList.forEach(e => { // log it to console for now, dedicated tab for 'error' channels needed
console.error(`failed to import ${e[2]}. Url to channel: ${e[1]}.`)
})
showToast(this.$t('Settings.Data Settings.One or more subscriptions were unable to be imported'))
} else {
showToast(this.$t('Settings.Data Settings.All subscriptions have been successfully imported'))
}
}).finally(_ => {
this.updateShowProgressBar(false)
})
},
exportSubscriptions: function (option) {
this.showExportSubscriptionsPrompt = false
if (option === null) {
return
}
switch (option) {
case 'freetube':
this.exportFreeTubeSubscriptions()
break
case 'youtubenew':
this.exportCsvYouTubeSubscriptions()
break
case 'youtube':
this.exportYouTubeSubscriptions()
break
case 'youtubeold':
this.exportOpmlYouTubeSubscriptions()
break
case 'newpipe':
this.exportNewPipeSubscriptions()
break
}
},
exportFreeTubeSubscriptions: async function () {
const subscriptionsDb = this.profileList.map((profile) => {
return JSON.stringify(profile)
}).join('\n') + '\n'// a trailing line is expected
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'freetube-subscriptions-' + dateStr + '.db'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['db']
}
]
}
await this.promptAndWriteToFile(options, subscriptionsDb, this.$t('Settings.Data Settings.Subscriptions have been successfully exported'))
},
exportYouTubeSubscriptions: async function () {
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'youtube-subscriptions-' + dateStr + '.json'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['json']
}
]
}
const subscriptionsObject = this.profileList[0].subscriptions.map((channel) => {
const object = {
contentDetails: {
activityType: 'all',
newItemCount: 0,
totalItemCount: 0
},
etag: '',
id: '',
kind: 'youtube#subscription',
snippet: {
channelId: channel.id,
description: '',
publishedAt: new Date(),
resourceId: {
channelId: channel.id,
kind: 'youtube#channel'
},
thumbnails: {
default: {
url: channel.thumbnail
},
high: {
url: channel.thumbnail
},
medium: {
url: channel.thumbnail
}
},
title: channel.name
}
}
return object
})
await this.promptAndWriteToFile(options, JSON.stringify(subscriptionsObject), this.$t('Settings.Data Settings.Subscriptions have been successfully exported'))
},
exportOpmlYouTubeSubscriptions: async function () {
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'youtube-subscriptions-' + dateStr + '.opml'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['opml']
}
]
}
let opmlData = '<opml version="1.1"><body><outline text="YouTube Subscriptions" title="YouTube Subscriptions">'
this.profileList[0].subscriptions.forEach((channel) => {
const escapedName = escapeHTML(channel.name)
const channelOpmlString = `<outline text="${escapedName}" title="${escapedName}" type="rss" xmlUrl="https://www.youtube.com/feeds/videos.xml?channel_id=${channel.id}"/>`
opmlData += channelOpmlString
})
opmlData += '</outline></body></opml>'
await this.promptAndWriteToFile(options, opmlData, this.$t('Settings.Data Settings.Subscriptions have been successfully exported'))
},
exportCsvYouTubeSubscriptions: async function () {
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'youtube-subscriptions-' + dateStr + '.csv'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['csv']
}
]
}
let exportText = 'Channel ID,Channel URL,Channel title\n'
this.profileList[0].subscriptions.forEach((channel) => {
const channelUrl = `https://www.youtube.com/channel/${channel.id}`
let channelName = channel.name
if (channelName.search(',') !== -1) { // add quotations and escape existing quotations if channel has comma in name
channelName = `"${channelName.replaceAll('"', '""')}"`
}
exportText += `${channel.id},${channelUrl},${channelName}\n`
})
exportText += '\n'
await this.promptAndWriteToFile(options, exportText, this.$t('Settings.Data Settings.Subscriptions have been successfully exported'))
},
exportNewPipeSubscriptions: async function () {
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'newpipe-subscriptions-' + dateStr + '.json'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Subscription File'),
extensions: ['json']
}
]
}
const newPipeObject = {
app_version: '0.19.8',
app_version_int: 953,
subscriptions: []
}
this.profileList[0].subscriptions.forEach((channel) => {
const channelUrl = `https://www.youtube.com/channel/${channel.id}`
const subscription = {
service_id: 0,
url: channelUrl,
name: channel.name
}
newPipeObject.subscriptions.push(subscription)
})
await this.promptAndWriteToFile(options, JSON.stringify(newPipeObject), this.$t('Settings.Data Settings.Subscriptions have been successfully exported'))
},
importHistory: async function () {
const options = {
properties: ['openFile'],
filters: [
{
name: this.$t('Settings.Data Settings.History File'),
extensions: ['db', 'json']
}
]
}
const response = await showOpenDialog(options)
if (response.canceled || response.filePaths?.length === 0) {
return
}
let textDecode
try {
textDecode = await readFileFromDialog(response)
} catch (err) {
const message = this.$t('Settings.Data Settings.Unable to read file')
showToast(`${message}: ${err}`)
return
}
response.filePaths.forEach(filePath => {
if (filePath.endsWith('.db')) {
this.importFreeTubeHistory(textDecode.split('\n'))
} else if (filePath.endsWith('.json')) {
this.importYouTubeHistory(JSON.parse(textDecode))
}
})
},
importFreeTubeHistory(textDecode) {
textDecode.pop()
const requiredKeys = [
'author',
'authorId',
'description',
'isLive',
'lengthSeconds',
'published',
'timeWatched',
'title',
'type',
'videoId',
'viewCount',
'watchProgress',
]
const optionalKeys = [
// `_id` absent if marked as watched manually
'_id',
'lastViewedPlaylistId',
]
const ignoredKeys = [
'paid',
]
textDecode.forEach((history) => {
const historyData = JSON.parse(history)
// We would technically already be done by the time the data is parsed,
// however we want to limit the possibility of malicious data being sent
// to the app, so we'll only grab the data we need here.
const historyObject = {}
Object.keys(historyData).forEach((key) => {
if (requiredKeys.includes(key) || optionalKeys.includes(key)) {
historyObject[key] = historyData[key]
} else if (!ignoredKeys.includes(key)) {
showToast(`Unknown data key: ${key}`)
}
// Else do not import the key
})
const historyObjectKeysSet = new Set(Object.keys(historyObject))
const missingKeys = requiredKeys.filter(x => !historyObjectKeysSet.has(x))
if (missingKeys.length > 0) {
showToast(this.$t('Settings.Data Settings.History object has insufficient data, skipping item'))
console.error('Missing Keys: ', missingKeys, historyData)
} else {
this.updateHistory(historyObject)
}
})
showToast(this.$t('Settings.Data Settings.All watched history has been successfully imported'))
},
importYouTubeHistory(historyData) {
const filterPredicate = item =>
item.products.includes('YouTube') &&
item.titleUrl != null && // removed video doesnt contain url...
item.titleUrl.includes('www.youtube.com/watch?v') &&
item.details == null // dont import ads
const filteredHistoryData = historyData.filter(filterPredicate)
// remove 'Watched' and translated variants from start of title
// so we get the common string prefix for all the titles
const getCommonStart = (allTitles) => {
const watchedTitle = allTitles[0].split(' ')
allTitles.forEach((title) => {
const splitTitle = title.split(' ')
for (let wtIndex = 0; wtIndex <= watchedTitle.length; wtIndex++) {
if (!splitTitle.includes(watchedTitle[wtIndex])) {
watchedTitle.splice(wtIndex, watchedTitle.length - wtIndex)
}
}
})
return watchedTitle.join(' ')
}
const commonStart = getCommonStart(filteredHistoryData.map(e => e.title))
// We would technically already be done by the time the data is parsed,
// however we want to limit the possibility of malicious data being sent
// to the app, so we'll only grab the data we need here.
const keyMapping = {
title: [{ importKey: 'title', predicate: item => item.slice(commonStart.length) }], // Removes the "Watched " term on the title
titleUrl: [{ importKey: 'videoId', predicate: item => item.replaceAll(/https:\/\/www\.youtube\.com\/watch\?v=/gi, '') }], // Extracts the video ID
time: [{ importKey: 'timeWatched', predicate: item => new Date(item).valueOf() }],
subtitles: [
{ importKey: 'author', predicate: item => item[0].name ?? '' },
{ importKey: 'authorId', predicate: item => item[0].url?.replaceAll(/https:\/\/www\.youtube\.com\/channel\//gi, '') ?? '' },
],
}
const knownKeys = [
'header',
'description',
'products',
'details',
'activityControls',
].concat(Object.keys(keyMapping))
filteredHistoryData.forEach(element => {
const historyObject = {}
Object.keys(element).forEach((key) => {
if (!knownKeys.includes(key)) {
showToast(`Unknown data key: ${key}`)
} else {
const mapping = keyMapping[key]
if (mapping && Array.isArray(mapping)) {
mapping.forEach(item => {
historyObject[item.importKey] = item.predicate(element[key])
})
}
}
})
if (Object.keys(historyObject).length < keyMapping.length - 1) {
showToast(this.$t('Settings.Data Settings.History object has insufficient data, skipping item'))
} else {
// YouTube history export does not have this data, setting some defaults.
historyObject.type = 'video'
historyObject.published = historyObject.timeWatched ?? 1
historyObject.description = ''
historyObject.lengthSeconds = null
historyObject.watchProgress = 1
historyObject.isLive = false
this.updateHistory(historyObject)
}
})
showToast(this.$t('Settings.Data Settings.All watched history has been successfully imported'))
},
exportHistory: async function () {
const historyDb = this.historyCacheSorted.map((historyEntry) => {
return JSON.stringify(historyEntry)
}).join('\n') + '\n'
const dateStr = getTodayDateStrLocalTimezone()
const exportFileName = 'freetube-history-' + dateStr + '.db'
const options = {
defaultPath: exportFileName,
filters: [
{
name: this.$t('Settings.Data Settings.Playlist File'),
extensions: ['db']
}
]
}
await this.promptAndWriteToFile(options, historyDb, this.$t('Settings.Data Settings.All watched history has been successfully exported'))
},
importPlaylists: async function () {
const options = {
properties: ['openFile'],
filters: [
{
name: this.$t('Settings.Data Settings.Playlist File'),
extensions: ['db']
}
]
}
const response = await showOpenDialog(options)
if (response.canceled || response.filePaths?.length === 0) {
return
}
let data
try {
data = await readFileFromDialog(response)
} catch (err) {
const message = this.$t('Settings.Data Settings.Unable to read file')
showToast(`${message}: ${err}`)
return
}
let playlists = null
// for the sake of backwards compatibility,
// check if this is the old JSON array export (used until version 0.19.1),
// that didn't match the actual database format
const trimmedData = data.trim()
if (trimmedData[0] === '[' && trimmedData[trimmedData.length - 1] === ']') {
playlists = JSON.parse(trimmedData)
} else {
// otherwise assume this is the correct database format,
// which is also what we export now (used in 0.20.0 and later versions)
data = data.split('\n')
data.pop()
playlists = data.map(playlistJson => JSON.parse(playlistJson))
}
const requiredKeys = [
'playlistName',
'videos',
]
const optionalKeys = [
'description',
'createdAt',
]
const ignoredKeys = [
'_id',
'title',
'type',
'protected',
'lastUpdatedAt',
'lastPlayedAt',
'removeOnWatched',
'thumbnail',
'channelName',
'channelId',
'playlistId',
'videoCount',
]
const requiredVideoKeys = [
'videoId',
'title',
'author',
'authorId',
'lengthSeconds',
'timeAdded',
// `playlistItemId` should be optional for backward compatibility
// 'playlistItemId',
]
playlists.forEach((playlistData) => {
// We would technically already be done by the time the data is parsed,
// however we want to limit the possibility of malicious data being sent
// to the app, so we'll only grab the data we need here.
const playlistObject = {}
Object.keys(playlistData).forEach((key) => {
if ([requiredKeys, optionalKeys, ignoredKeys].every((ks) => !ks.includes(key))) {
const message = `${this.$t('Settings.Data Settings.Unknown data key')}: ${key}`
showToast(message)
} else if (key === 'videos') {
const videoArray = []
playlistData.videos.forEach((video) => {
const videoPropertyKeys = Object.keys(video)
const videoObjectHasAllRequiredKeys = requiredVideoKeys.every((k) => videoPropertyKeys.includes(k))
if (videoObjectHasAllRequiredKeys) {
videoArray.push(video)
}
})
playlistObject[key] = videoArray
} else if (!ignoredKeys.includes(key)) {
// Do nothing for keys to be ignored
playlistObject[key] = playlistData[key]
}
})
const playlistObjectKeys = Object.keys(playlistObject)
const playlistObjectHasAllRequiredKeys = requiredKeys.every((k) => playlistObjectKeys.includes(k))
if (playlistObjectHasAllRequiredKeys) {
const existingPlaylist = this.allPlaylists.find((playlist) => {
return playlist.playlistName === playlistObject.playlistName
})
if (existingPlaylist !== undefined) {
playlistObject.videos.forEach((video) => {
let videoExists = false
if (video.playlistItemId != null) {
// Find by `playlistItemId` if present
videoExists = existingPlaylist.videos.some((x) => {
// Allow duplicate (by videoId) videos to be added
return x.videoId === video.videoId && x.playlistItemId === video.playlistItemId
})
} else {
// Older playlist exports have no `playlistItemId` but have `timeAdded`
// Which might be duplicate for copied playlists with duplicate `videoId`
videoExists = existingPlaylist.videos.some((x) => {
// Allow duplicate (by videoId) videos to be added
return x.videoId === video.videoId && x.timeAdded === video.timeAdded
})
}
if (!videoExists) {
// Keep original `timeAdded` value
const payload = {