-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathplex_exporter_importer.py
executable file
·1449 lines (1324 loc) · 56.3 KB
/
plex_exporter_importer.py
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
#!/usr/bin/python3
#-*- coding: utf-8 -*-
"""
The use case of this script is the following:
Export plex metadata to a database file that can then be read from to import the data back (on a different plex instance)
The following is supported:
metadata, advanced metadata, watched status, posters, backgrounds (arts), collections, playlists, intro markers, chapter thumbnails and server settings
Requirements (python3 -m pip install [requirement]):
requests
Setup:
Fill the variables below firstly, then run the script.
Notes:
1. Under the following situations, it is REQUIRED that the script is run on the target server and that the script is run using the root user (administrative user):
1. "intro_marker" when importing
2. "chapter_thumbnail" when importing
2. Importing chapter thumbnails on a non-linux system is not possible.
"""
plex_ip = ''
plex_port = ''
plex_api_token = ''
#ADVANCED SETTINGS
#Hardcode the folder where the plex database is in
#Leave empty unless really needed
database_folder = ''
plex_linux_user = 'plex'
plex_linux_group = 'plex'
from sys import platform
from os import getenv, path, listdir
from sqlite3 import connect
from datetime import datetime
from time import perf_counter
linux_platform = platform == 'linux'
if linux_platform == True:
from pwd import getpwnam
from grp import getgrnam
from os import chmod, chown, makedirs
# Environmental Variables
plex_ip = getenv('plex_ip', plex_ip)
plex_port = getenv('plex_port', plex_port)
plex_api_token = getenv('plex_api_token', plex_api_token)
database_folder = getenv('database_folder', database_folder)
base_url = f"http://{plex_ip}:{plex_port}"
request_cache = {}
guid_map = {}
if linux_platform == True:
plex_linux_user = getenv('plex_linux_user', plex_linux_user)
plex_linux_group = getenv('plex_linux_group', plex_linux_group)
plex_linux_user = getpwnam(plex_linux_user).pw_uid
plex_linux_group = getgrnam(plex_linux_group).gr_gid
#media types tuple content: metadata keys, plex type id, table creation command, plex children type id, plex children types
media_types = {
'movie': (
(
'title', 'titleSort', 'originalTitle',
'originallyAvailableAt', 'contentRating', 'userRating',
'studio', 'tagline', 'summary',
'Genre', 'Writer', 'Director'
),
1,
"""
CREATE TABLE IF NOT EXISTS movie (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
originalTitle VARCHAR(255),
originallyAvailableAt VARCHAR(10),
contentRating VARCHAR(15),
userRating FLOAT,
studio VARCHAR(255),
tagline VARCHAR(255),
summary TEXT,
Genre TEXT,
Writer TEXT,
Director TEXT,
languageOverride VARCHAR(5),
useOriginalTitle INTEGER(1),
watched_status TEXT,
hash VARCHAR(255),
chapter_thumbnails BLOB,
poster BLOB,
art BLOB
);
""",
1,
['movie']
),
'show': (
(
'title', 'titleSort', 'originalTitle',
'originallyAvailableAt', 'contentRating', 'userRating',
'studio', 'tagline', 'summary',
'Genre'
),
2,
"""
CREATE TABLE IF NOT EXISTS show (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
originalTitle VARCHAR(255),
originallyAvailableAt VARCHAR(10),
contentRating VARCHAR(15),
userRating FLOAT,
studio VARCHAR(255),
tagline VARCHAR(255),
summary TEXT,
Genre TEXT,
episodeSort INTEGER(1),
autoDeletionItemPolicyUnwatchedLibrary INTEGER(2),
autoDeletionItemPolicyWatchedLibrary INTEGER(3),
flattenSeasons INTEGER(1),
showOrdering VARCHAR(10),
languageOverride VARCHAR(5),
useOriginalTitle INTEGER(1),
poster BLOB,
art BLOB
);
""",
4,
['show','season','episode']
),
'season': (
(
'title', 'summary'
),
3,
"""
CREATE TABLE IF NOT EXISTS season (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
summary TEXT,
poster BLOB,
art BLOB
);
""",
4,
['season','episode']
),
'episode': (
(
'title', 'titleSort',
'originallyAvailableAt', 'contentRating', 'userRating',
'summary',
'Writer', 'Director'
),
4,
"""
CREATE TABLE IF NOT EXISTS episode (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
originallyAvailableAt VARCHAR(10),
contentRating VARCHAR(15),
userRating FLOAT,
summary TEXT,
Writer TEXT,
Director TEXT,
intro_start INTEGER,
intro_end INTEGER,
watched_status TEXT,
hash VARCHAR(255),
chapter_thumbnails BLOB,
poster BLOB,
art BLOB
);
""",
4,
['episode']
),
'artist': (
(
'title', 'titleSort', 'summary',
'Genre', 'Style', 'Mood', 'Country', 'Similar'
),
8,
"""
CREATE TABLE IF NOT EXISTS artist (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
summary TEXT,
Genre TEXT,
Style TEXT,
Mood TEXT,
Country TEXT,
Similar TEXT,
albumSort INTEGER(1),
poster BLOB,
art BLOB
);
""",
10,
['artist','album','track']
),
'album': (
(
'title', 'titleSort',
'originallyAvailableAt', 'contentRating', 'userRating',
'studio','summary',
'Genre', 'Style', 'Mood'
),
9,
"""
CREATE TABLE IF NOT EXISTS album (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
originallyAvailableAt VARCHAR(10),
contentRating VARCHAR(15),
userRating FLOAT,
studio VARCHAR(255),
summary TEXT,
Genre TEXT,
Style TEXT,
Mood TEXT,
poster BLOB,
art BLOB
);
""",
10,
['album','track']
),
'track': (
(
'title', 'originalTitle',
'contentRating', 'userRating', '[index]', 'parentIndex',
'Mood'
),
10,
"""
CREATE TABLE IF NOT EXISTS track (
rating_key VARCHAR(15) PRIMARY KEY,
guid VARCHAR(120),
updated_at INTEGER(8),
title VARCHAR(255),
originalTitle VARCHAR(255),
contentRating VARCHAR(15),
userRating FLOAT,
[index] INTEGER,
parentIndex INTEGER,
Mood TEXT
);
""",
10,
['track']
),
'collection': (
(
'title', 'titleSort', 'contentRating', 'summary',
'collectionMode', 'collectionSort',
'subtype'
),
18,
"""
CREATE TABLE IF NOT EXISTS collection (
rating_key VARCHAR(15) PRIMARY KEY,
updated_at INTEGER(8),
title VARCHAR(255),
titleSort VARCHAR(255),
contentRating TEXT,
summary TEXT,
collectionMode INTEGER(1),
collectionSort INTEGER(1),
subtype VARCHAR(10),
guids TEXT,
poster BLOB,
art BLOB
);
""",
18,
['collection']
),
'playlist': (
(
'title', 'summary'
),
15,
"""
CREATE TABLE IF NOT EXISTS playlist (
rating_key VARCHAR(15) PRIMARY KEY,
updated_at INTEGER(8),
user_id INTEGER(10),
title VARCHAR(255),
summary TEXT,
playlistType VARCHAR(15),
guids TEXT,
poster BLOB,
art BLOB
);
""",
15,
['playlist']
),
'server': (
(
'FriendlyName','sendCrashReports','PushNotificationsEnabled','logDebug','LogVerbose','ButlerUpdateChannel',
'ManualPortMappingMode', 'ManualPortMappingPort', 'WanTotalMaxUploadRate', 'WanPerStreamMaxUploadRate',
'FSEventLibraryUpdatesEnabled', 'FSEventLibraryPartialScanEnabled', 'watchMusicSections', 'ScheduledLibraryUpdatesEnabled', 'ScheduledLibraryUpdateInterval', 'autoEmptyTrash', 'allowMediaDeletion', 'OnDeckWindow', 'OnDeckLimit', 'OnDeckIncludePremieres', 'SmartShuffleMusic', 'MusicSeparateAlbumTypes', 'ScannerLowPriority', 'GenerateBIFBehavior', 'GenerateIntroMarkerBehavior', 'GenerateChapterThumbBehavior', 'LoudnessAnalysisBehavior', 'MusicAnalysisBehavior', 'LocationVisibility',
'EnableIPv6', 'secureConnections', 'customCertificatePath', 'customCertificateKey', 'customCertificateDomain', 'PreferredNetworkInterface', 'DisableTLSv1_0', 'GdmEnabled', 'WanPerUserStreamCount', 'LanNetworksBandwidth', 'MinutesAllowedPaused', 'TreatWanIpAsLocal', 'RelayEnabled', 'customConnections', 'allowedNetworks', 'WebHooksEnabled',
'TranscoderQuality', 'TranscoderTempDirectory', 'TranscoderThrottleBuffer', 'TranscoderH264BackgroundPreset', 'TranscoderToneMapping', 'TranscoderCanOnlyRemuxVideo', 'HardwareAcceleratedCodecs', 'HardwareAcceleratedEncoders', 'TranscodeCountLimit',
'DlnaEnabled', 'DlnaClientPreferences', 'DlnaReportTimeline', 'DlnaDefaultProtocolInfo', 'DlnaDeviceDiscoveryInterval', 'DlnaAnnouncementLeaseTime', 'DlnaDescriptionIcons',
'ButlerStartHour', 'ButlerEndHour', 'ButlerTaskBackupDatabase', 'ButlerDatabaseBackupPath', 'ButlerTaskOptimizeDatabase', 'ButlerTaskCleanOldBundles', 'ButlerTaskCleanOldCacheFiles', 'ButlerTaskRefreshLocalMedia', 'ButlerTaskRefreshLibraries', 'ButlerTaskUpgradeMediaAnalysis', 'ButlerTaskRefreshPeriodicMetadata', 'ButlerTaskDeepMediaAnalysis', 'ButlerTaskReverseGeocode', 'ButlerTaskGenerateAutoTags',
'CinemaTrailersType', 'CinemaTrailersFromLibrary', 'CinemaTrailersFromTheater', 'CinemaTrailersFromBluRay', 'CinemaTrailersPrerollID', 'GlobalMusicVideoPath'
),
-1,
"""
CREATE TABLE IF NOT EXISTS server (
machine_id TEXT,
FriendlyName TEXT,
sendCrashReports TEXT,
PushNotificationsEnabled TEXT,
logDebug TEXT,
LogVerbose TEXT,
ButlerUpdateChannel TEXT,
ManualPortMappingMode TEXT,
ManualPortMappingPort TEXT,
WanTotalMaxUploadRate TEXT,
WanPerStreamMaxUploadRate TEXT,
FSEventLibraryUpdatesEnabled TEXT,
FSEventLibraryPartialScanEnabled TEXT,
watchMusicSections TEXT,
ScheduledLibraryUpdatesEnabled TEXT,
ScheduledLibraryUpdateInterval TEXT,
autoEmptyTrash TEXT,
allowMediaDeletion TEXT,
OnDeckWindow TEXT,
OnDeckLimit TEXT,
OnDeckIncludePremieres TEXT,
SmartShuffleMusic TEXT,
MusicSeparateAlbumTypes TEXT,
ScannerLowPriority TEXT,
GenerateBIFBehavior TEXT,
GenerateIntroMarkerBehavior TEXT,
GenerateChapterThumbBehavior TEXT,
LoudnessAnalysisBehavior TEXT,
MusicAnalysisBehavior TEXT,
LocationVisibility TEXT,
EnableIPv6 TEXT,
secureConnections TEXT,
customCertificatePath TEXT,
customCertificateKey TEXT,
customCertificateDomain TEXT,
PreferredNetworkInterface TEXT,
DisableTLSv1_0 TEXT,
GdmEnabled TEXT,
WanPerUserStreamCount TEXT,
LanNetworksBandwidth TEXT,
MinutesAllowedPaused TEXT,
TreatWanIpAsLocal TEXT,
RelayEnabled TEXT,
customConnections TEXT,
allowedNetworks TEXT,
WebHooksEnabled TEXT,
TranscoderQuality TEXT,
TranscoderTempDirectory TEXT,
TranscoderThrottleBuffer TEXT,
TranscoderH264BackgroundPreset TEXT,
TranscoderToneMapping TEXT,
TranscoderCanOnlyRemuxVideo TEXT,
HardwareAcceleratedCodecs TEXT,
HardwareAcceleratedEncoders TEXT,
TranscodeCountLimit TEXT,
DlnaEnabled TEXT,
DlnaClientPreferences TEXT,
DlnaReportTimeline TEXT,
DlnaDefaultProtocolInfo TEXT,
DlnaDeviceDiscoveryInterval TEXT,
DlnaAnnouncementLeaseTime TEXT,
DlnaDescriptionIcons TEXT,
ButlerStartHour TEXT,
ButlerEndHour TEXT,
ButlerTaskBackupDatabase TEXT,
ButlerDatabaseBackupPath TEXT,
ButlerTaskOptimizeDatabase TEXT,
ButlerTaskCleanOldBundles TEXT,
ButlerTaskCleanOldCacheFiles TEXT,
ButlerTaskRefreshLocalMedia TEXT,
ButlerTaskRefreshLibraries TEXT,
ButlerTaskUpgradeMediaAnalysis TEXT,
ButlerTaskRefreshPeriodicMetadata TEXT,
ButlerTaskDeepMediaAnalysis TEXT,
ButlerTaskReverseGeocode TEXT,
ButlerTaskGenerateAutoTags TEXT,
CinemaTrailersType TEXT,
CinemaTrailersFromLibrary TEXT,
CinemaTrailersFromTheater TEXT,
CinemaTrailersFromBluRay TEXT,
CinemaTrailersPrerollID TEXT,
GlobalMusicVideoPath TEXT
)
""",
-1,
[]
)
}
process_summary = {
'metadata': "The standard plex metadata like title, summary, tags and more.",
'advanced_metadata': "The advanced plex settings (metadata) for media",
'watched_status': "The watched status of the media for every user: watched, not watched or partially watched.",
'poster': "The (custom) poster of movies, shows, seasons, artists and albums.",
'episode_poster': "The (custom) poster of episodes.",
'art': "The (custom) art of movies, shows, seasons, artists and albums.",
'episode_art': "The (custom) art of episodes.",
'collection': "The collections in every library",
'playlist': "The playlists of every user",
'intro_marker': "The intro marker of episodes, which describes the beginning and end of the intro.",
'chapter_thumbnail': "The by plex automatically generated thumbnails for chapters.",
'server_settings': "The settings of the server"
}
process_types = ('import','export','reset')
advanced_metadata_keys = ('languageOverride','useOriginalTitle','episodeSort','autoDeletionItemPolicyUnwatchedLibrary','autoDeletionItemPolicyWatchedLibrary','flattenSeasons','showOrdering','albumSort')
advanced_collection_keys = ('collectionMode','collectionSort')
metadata_skip_keys = ('rating_key','guid','updated_at','poster','art','watched_status','intro_start','intro_end','hash','subtype','guids') + advanced_metadata_keys + advanced_collection_keys + media_types['server'][0]
def _leave(db, plex_db=None, e=None):
#called upon early exit of script
print('Shutting down...')
db.commit()
if plex_db != None:
plex_db.commit()
print('Progress saved')
if e != None:
print('AN ERROR OCCURED. ALL YOUR PROGRESS IS SAVED. PLEASE SHARE THE FOLLOWING WITH THE DEVELOPER:')
raise e
exit(0)
def _req_cache(ssn, url, params={}, headers={}):
#use for general requests in the hope that it is requested multiple times
#and that way the cached result from the first time is returned
global request_cache
if not url in request_cache:
request_cache[url] = ssn.get(url, params=params, headers=headers).json()
return request_cache[url]
def _guid_to_ratingkey(ssn, guid: str):
global guid_map
rating_key = guid_map.get(guid)
if rating_key == None:
sections = _req_cache(ssn, f'{base_url}/library/sections')['MediaContainer'].get('Directory',[])
for lib in sections:
if lib['type'] == 'movie':
media_type = '1'
elif lib['type'] == 'show':
media_type = '4'
else: continue
lib_output = _req_cache(ssn, f'{base_url}/library/sections/{lib["key"]}/all', params={'type': media_type, 'includeGuids': '1'})['MediaContainer'].get('Metadata',[])
for media in lib_output:
media_guid = str(media['Guid'])
if media_guid == guid:
rating_key = media['ratingKey']
guid_map[media_guid] = media['ratingKey']
break
else:
continue
break
else:
rating_key = None
return rating_key
def _export(
type: str, data: dict, ssn, cursor, user_data: tuple, watched_map: dict, timestamp_map: dict,
target_metadata: bool, target_advanced_metadata: bool, target_watched: bool, target_intro_markers: bool, target_chapter_thumbnail: bool,
target_poster: bool, target_episode_poster: bool, target_art: bool, target_episode_art: bool,
database_folder=None, hash_map=None, user_id=None
):
user_ids, user_tokens = user_data
#extract different data based on the type
if type in media_types:
keys = media_types[type][0]
else:
#unknown type of source
return 'Unknown source type when trying to extract data (internal error)'
#if requested, export server settings here and return function (server settings is a "special" case)
if type == 'server':
machine_id = _req_cache(ssn, f"{base_url}/")['MediaContainer']['machineIdentifier']
cursor.execute(f"DELETE FROM {type} WHERE machine_id = ?", (machine_id,))
db_keys, db_values = ['machine_id'], [machine_id]
prefs = _req_cache(ssn, f'{base_url}/:/prefs')['MediaContainer']['Setting']
for pref in prefs:
if not pref['id'] in media_types['server'][0]: continue
db_keys.append(pref['id'])
db_values.append(pref['value'])
#write to the database
comm = f"""
INSERT INTO {type} ({",".join(db_keys)})
VALUES ({",".join(['?'] * len(db_keys))})
"""
cursor.execute(comm, db_values)
return
rating_key = data['ratingKey']
#skip media if it hasn't been edited since last time (or it isn't matched to any series)
updated_at = timestamp_map[type].get(rating_key)
if updated_at != None:
if updated_at == data.get('updatedAt',0):
return
else:
cursor.execute(f"DELETE FROM {type} WHERE rating_key = '{rating_key}'")
elif type == 'collection':
#collection either hasn't been added to db yet or has been imported after exporting
cursor.execute(f'DELETE FROM {type} WHERE title = "{data["title"]}";')
#if requested, export collection here and return function (collection is a "special" case)
if type == 'collection':
if data.get('smart') == '1': return
#export metadata
collection_info = ssn.get(f'{base_url}/library/collections/{data["ratingKey"]}', params={'includePreferences': '1'}).json()['MediaContainer']['Metadata'][0]
db_keys, db_values = ['rating_key','updated_at'], [rating_key, collection_info.get('updatedAt',0)]
for key in keys:
if key == 'titleSort':
value = collection_info.get('titleSort', collection_info.get('title', ''))
else:
value = collection_info.get(key)
if value != None:
db_keys.append(key)
db_values.append(value)
#export preferences
db_keys += [s['id'] for s in collection_info['Preferences']['Setting']]
db_values += [s['value'] for s in collection_info['Preferences']['Setting']]
#export entries
collection_content = ssn.get(f'{base_url}/library/collections/{data["ratingKey"]}/children', params={'includeGuids': '1'}).json()['MediaContainer'].get('Metadata',[])
db_keys.append('guids')
db_values.append("|".join(str(m['Guid']) for m in collection_content if 'Guid' in m))
#export images
if 'thumb' in collection_info:
r = ssn.get(f'{base_url}{collection_info["thumb"]}')
if r.status_code == 200:
db_keys.append('poster')
db_values.append(r.content)
if 'art' in collection_info:
r = ssn.get(f'{base_url}{collection_info["art"]}')
if r.status_code == 200:
db_keys.append('art')
db_values.append(r.content)
#write to database
comm = f"""
INSERT INTO {type} ({",".join(db_keys)})
VALUES ({",".join(['?'] * len(db_keys))})
"""
cursor.execute(comm, db_values)
return
#if requested, export playlist here and return function (playlist is a "special" case)
if type == 'playlist':
if data.get('smart') == True: return
#export metadata
db_keys = ['rating_key','updated_at','user_id','title','summary','playlistType']
db_values = [rating_key, data.get('updatedAt',0), user_id, data.get('title'), data.get('summary'), data.get('playlistType')]
#export entries
playlist_content = ssn.get(f'{base_url}{data["key"]}', params={'includeGuids': '1'}).json()['MediaContainer'].get('Metadata',[])
db_keys.append('guids')
db_values.append("|".join(str(m['Guid']) for m in playlist_content if 'Guid' in m))
#export images
if 'thumb' in data:
r = ssn.get(f'{base_url}{data["thumb"]}')
if r.status_code == 200:
db_keys.append('poster')
db_values.append(r.content)
if 'art' in data:
r = ssn.get(f'{base_url}{data["thumb"]}')
if r.status_code == 200:
db_keys.append('art')
db_values.append(r.content)
#write to database
comm = f"""
INSERT INTO {type} ({",".join(db_keys)})
VALUES ({",".join(['?'] * len(db_keys))})
"""
cursor.execute(comm, db_values)
return
if not 'Guid' in data: return
#request certain media again when we need it's metadata (lib output doesn't show all)
if (target_metadata == True and type != 'season') \
or (target_intro_markers == True and type == 'episode') \
or (target_chapter_thumbnail == True and type in ('movie','episode')) \
or (target_advanced_metadata == True and type == 'movie'):
media_info = ssn.get(f'{base_url}/library/metadata/{rating_key}', params={'includeGuids': '1', 'includeMarkers': '1', 'includeChapters': '1', 'includePreferences': '1'})
if media_info.status_code != 200: return
media_info = media_info.json()['MediaContainer']['Metadata'][0]
else:
media_info = data
#extract data and built up key-value pair for db
db_keys = ['rating_key','guid','updated_at']
db_values = [rating_key,str(media_info['Guid']),media_info.get('updatedAt',0)]
if target_metadata == True:
for key in keys:
if key[0].isupper():
value = ",".join([x['tag'] for x in media_info.get(key, [])]) or None
elif key == '[index]':
value = media_info.get('index')
elif key == 'titleSort' and type != 'track':
value = media_info.get('titleSort', media_info.get('title', ''))
else:
value = media_info.get(key)
if value != None:
db_keys.append(key)
db_values.append(value)
if target_advanced_metadata == True and type in ('movie','show','artist'):
db_keys += [s['id'] for s in media_info['Preferences']['Setting']]
db_values += [s['value'] for s in media_info['Preferences']['Setting']]
if target_watched == True and type in ('movie','episode'):
db_keys.append('watched_status')
db_watched = ['_admin',str(media_info.get('viewOffset', 'viewCount' in media_info))]
for user_id, user_token in zip(user_ids, user_tokens):
user_watched = str(watched_map.get(user_token, {}).get(rating_key, ''))
if user_watched == '': continue
db_watched += [user_id, user_watched]
db_values.append(",".join(db_watched))
if target_intro_markers == True and type in 'episode':
for marker in media_info.get('Marker',[]):
if marker['type'] == 'intro':
#intro marker found
db_keys += ['intro_start','intro_end']
db_values += [marker['startTimeOffset'], marker['endTimeOffset']]
break
if target_chapter_thumbnail == True and type in ('movie','episode'):
hash = hash_map[rating_key]
bundle = path.join(path.dirname(path.dirname(database_folder)), 'Media', 'localhost', hash[0], f'{hash[1:]}.bundle', 'Contents', 'Chapters')
# #check if media doesn't already have autogenerated thumbs and if hash matches
if path.isdir(bundle):
db_keys += ['hash','chapter_thumbnails']
db_values.append(hash)
db_values.append((b'\0' * 20).join(map(lambda c: open(path.join(bundle, c), 'rb').read(), listdir(bundle))))
if (target_poster == True and not type in ('episode','track')) or (target_episode_poster == True and type == 'episode'):
if 'thumb' in media_info:
r = ssn.get(f'{base_url}{media_info["thumb"]}')
if r.status_code == 200:
db_keys.append('poster')
db_values.append(r.content)
if (target_art == True and not type in ('episode','track')) or (target_episode_art == True and type == 'episode'):
if 'art' in media_info:
r = ssn.get(f'{base_url}{media_info["art"]}')
if r.status_code == 200:
db_keys.append('art')
db_values.append(r.content)
#write to the database
comm = f"""
INSERT INTO {type} ({",".join(db_keys)})
VALUES ({",".join(['?'] * len(db_keys))})
"""
cursor.execute(comm, db_values)
return
def _import(
type: str, data: dict, ssn, cursor, media_lib_id: str, user_data: tuple, watched_map: dict, timestamp_map: dict,
target_metadata: bool, target_advanced_metadata: bool, target_watched: bool, target_intro_markers: bool, target_chapter_thumbnail: bool,
target_poster: bool, target_episode_poster: bool, target_art: bool, target_episode_art: bool,
plex_cursor=None, database_folder=None, hash_map=None
):
user_ids, user_tokens = user_data
#import different data based on the type
if type in media_types:
media_type = media_types[type][1]
else:
return 'Unknown source type when trying to import data (internal error)'
if type in ('server','collection','playlist'):
machine_id = _req_cache(ssn, f"{base_url}/")['MediaContainer']['machineIdentifier']
if type == 'server':
cursor.execute(f"SELECT * FROM {type} WHERE machine_id = ?", (machine_id,))
server_settings = cursor.fetchone()
if server_settings == None: return
payload = dict(zip(media_types[type][0], server_settings[1:]))
ssn.put(f'{base_url}/:/prefs', params=payload)
return
if type == 'collection':
cursor.execute(f"SELECT * FROM {type};")
collections = cursor.fetchall()
collection_types = set([c[8] for c in collections])
target_keys = next(zip(*cursor.description))
sections = _req_cache(ssn, f'{base_url}/library/sections')['MediaContainer'].get('Directory',[])
#go through every library and check if a collection "fits" in it
for lib in sections:
if not lib['type'] in collection_types: continue
lib_output = ssn.get(f'{base_url}/library/sections/{lib["key"]}/all', params={'type': media_types[lib['type']][3], 'includeGuids': '1'}).json()['MediaContainer'].get('Metadata',[])
#guid -> ratingkey
lib_content = {str(m['Guid']): m['ratingKey'] for m in lib_output if 'Guid' in m}
collection_output = ssn.get(f'{base_url}/library/sections/{lib["key"]}/collections').json()['MediaContainer'].get('Metadata',[])
#title -> ratingkey
collection_content = dict(map(lambda c: (c['title'], c['ratingKey']), collection_output))
#go through every collection to check if it fits in library
for collection in collections:
collection_entries = collection[9].split("|")
collection_keys = [lib_content.get(str(e)) for e in collection_entries if str(e) in lib_content]
if len(collection_keys) == len(collection_entries):
#collection can go in library
#remove existing collection if present
old_ratingkey = collection_content.get(collection[2])
if old_ratingkey != None:
ssn.delete(f'{base_url}/library/collections/{old_ratingkey}')
#create collection
new_ratingkey = ssn.post(f'{base_url}/library/collections', params={'title': collection[2], 'smart': '0', 'sectionId': lib['key'], 'type': media_types[lib['type']][3], 'uri': f'server://{machine_id}/com.plexapp.plugins.library/library/metadata/{",".join(collection_keys)}'}).json()['MediaContainer']['Metadata'][0]['ratingKey']
#set poster
if collection[10] != None:
ssn.post(f'{base_url}/library/collections/{new_ratingkey}/posters', data=collection[10])
#set art
if collection[11] != None:
ssn.post(f'{base_url}/library/collections/{new_ratingkey}/arts', data=collection[11])
#set settings
payload = {
'type': media_type,
'id': new_ratingkey,
}
for option, value in zip(target_keys, collection):
if option in metadata_skip_keys: continue
payload[f'{option}.value'] = value or ''
payload[f'{option}.locked'] = 1
ssn.put(f'{base_url}/library/sections/{lib["key"]}/all', params=payload)
#set advanced settings
payload = {o: v for o, v in zip(target_keys, collection) if o in advanced_collection_keys}
ssn.put(f'{base_url}/library/metadata/{new_ratingkey}/prefs', params=payload)
return
if type == 'playlist':
cursor.execute(f"SELECT * FROM {type};")
playlists = cursor.fetchall()
for playlist in playlists:
if playlist[2] == '_admin': user_token = plex_api_token
else:
if not playlist[2] in user_ids: continue
user_token = user_tokens[user_ids.index(playlist[2])]
ssn.params.update({'X-Plex-Token': user_token})
user_playlists = _req_cache(ssn, f'{base_url}/playlists')['MediaContainer'].get('Metadata',[])
#delete already existing playlists with the name
for user_playlist in user_playlists:
if user_playlist['title'] == playlist[3]:
ssn.delete(f'{base_url}/playlists/{user_playlist["ratingKey"]}')
#create playlist
rating_keys = ",".join(filter(lambda x: x != None, (_guid_to_ratingkey(ssn, g) for g in playlist[6].split("|"))))
new_ratingkey = ssn.post(f'{base_url}/playlists', params={'type': playlist[5], 'title': playlist[3], 'smart': '0', 'uri': f'server://{machine_id}/com.plexapp.plugins.library/library/metadata/{rating_keys}'}).json()['MediaContainer']['Metadata'][0]['ratingKey']
#set summary
if playlist[4] or '' != '':
ssn.put(f'{base_url}/playlists/{new_ratingkey}', params={'summary': playlist[4]})
#set images
if playlist[7] or '' != '':
ssn.post(f'{base_url}/playlists/{new_ratingkey}/posters', data=playlist[7])
if playlist[8] or '' != '':
ssn.post(f'{base_url}/playlists/{new_ratingkey}/arts', data=playlist[8])
return
rating_key = data['ratingKey']
if not 'Guid' in data: return
#request certain media again when we need it's metadata (lib output doesn't show all)
if target_metadata == True and type != 'season':
media_info = ssn.get(f'{base_url}/library/metadata/{rating_key}', params={'includeGuids': '1', 'includeMarkers': '1'})
if media_info.status_code != 200: return
media_info = media_info.json()['MediaContainer']['Metadata'][0]
else:
media_info = data
#find media in database
guid = str(media_info['Guid'])
cursor.execute(f"SELECT * FROM {type} WHERE guid = ?", (guid,))
target = cursor.fetchone()
if target == None: return
target_keys = next(zip(*cursor.description))
#import data
if target_metadata == True:
payload = {
'type': media_type,
'id': rating_key,
'thumb.locked': 1,
'art.locked': 1
}
if type == 'album':
payload['artist.id.value'] = data['parentRatingKey']
#build the payload that sets all the values
for option, value in zip(target_keys, target):
if option in metadata_skip_keys: continue
elif option[0].isupper():
#list of labels
value = value or ''
value = value.split(",")
lower_option = option.lower()
#add tags
for offset, list_item in enumerate(value):
payload[f'{lower_option}[{offset}].tag.tag'] = list_item
#remove other tags
if option in media_info:
payload[f'{lower_option}[].tag.tag-'] = ",".join(map(lambda x: x['tag'], media_info[option]))
payload[f'{lower_option}.locked'] = 1
else:
#normal key value pair
payload[f'{option}.value'] = value or ''
payload[f'{option}.locked'] = 1
#upload to plex
ssn.put(f'{base_url}/library/sections/{media_lib_id}/all', params=payload)
if target_advanced_metadata == True and type in ('movie','show','artist'):
payload = {o: v for o, v in zip(target_keys, target) if o in advanced_metadata_keys}
ssn.put(f'{base_url}/library/metadata/{rating_key}/prefs', params=payload)
if 'poster' in target_keys and ((type != 'episode' and target_poster == True) or (type == 'episode' and target_episode_poster == True)):
ssn.post(f'{base_url}/library/metadata/{rating_key}/posters', data=target[target_keys.index('poster')])
if 'art' in target_keys and ((type != 'episode' and target_art == True) or (type == 'episode' and target_episode_art == True)):
ssn.post(f'{base_url}/library/metadata/{rating_key}/arts', data=target[target_keys.index('art')])
if 'watched_status' in target_keys and target_watched == True:
watched_info = target[target_keys.index('watched_status')].split(',')
for user, watched_state in zip(watched_info[::2], watched_info[1::2]):
if user == '_admin': user_token = plex_api_token
else:
if not user in user_ids: continue
user_token = user_tokens[user_ids.index(user)]
#set watched status of media for this user
if watched_state == 'True':
#mark watched
ssn.get(f'{base_url}/:/scrobble', params={'identifier': 'com.plexapp.plugins.library', 'key': rating_key, 'X-Plex-Token': user_token})
elif watched_state == 'False':
#mark not-watched
ssn.get(f'{base_url}/:/unscrobble', params={'identifier': 'com.plexapp.plugins.library', 'key': rating_key, 'X-Plex-Token': user_token})
elif watched_state.isdigit():
#mark partially watched
ssn.get(f'{base_url}/:/progress', params={'identifier': 'com.plexapp.plugins.library', 'key': rating_key, 'time': watched_state, 'state': 'stopped', 'X-Plex-Token': user_token})
if 'intro_start' in target_keys and 'intro_end' in target_keys and target_intro_markers == True:
#check if media already has intro marker
plex_cursor.execute("SELECT * FROM taggings WHERE text = 'intro' AND metadata_item_id = ?;", (rating_key,))
if plex_cursor.fetchone() == None:
#no intro marker exists so create one
d = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
plex_cursor.execute("SELECT tag_id FROM taggings WHERE text = 'intro';")
i = plex_cursor.fetchone()
if i == None:
#no id yet for intro's so make one that isn't taken yet
plex_cursor.execute("SELECT tag_id FROM taggings ORDER BY tag_id DESC;")
i = int(plex_cursor.fetchone()[0]) + 1
else:
i = i[0]
plex_cursor.execute(f"""
INSERT INTO taggings (
metadata_item_id,
tag_id,
[index],
text,
time_offset,
end_time_offset,
thumb_url,
created_at,
extra_data
) VALUES (?, ?, 0, 'intro', ?, ?, '', ?, 'pv%3Aversion=5');
""", (rating_key, i, target[target_keys.index('intro_start')], target[target_keys.index('intro_end')], d))
else:
#intro marker exists so update timestamps
plex_cursor.execute("""
UPDATE taggings
SET
time_offset = ?,
end_time_offset = ?
WHERE
text = 'intro'
AND metadata_item_id = ?;
""", (target[target_keys.index('intro_start')], target[target_keys.index('intro_end')], rating_key))
if 'hash' in target_keys and 'chapter_thumbnails' in target_keys and target_chapter_thumbnail == True:
hash = hash_map[rating_key]
bundle = path.join(path.dirname(path.dirname(database_folder)), 'Media', 'localhost', hash[0], f'{hash[1:]}.bundle', 'Contents', 'Chapters')
#check if media doesn't already have autogenerated thumbs and if hash matches
if target[target_keys.index('hash')] == hash and not path.isdir(bundle):
thumbs = target[target_keys.index('chapter_thumbnails')].split(b'\0' * 20)
#create folder path to put thumbs in
bundle = path.dirname(path.dirname(database_folder))
for folder in ('Media', 'localhost', hash[0], f'{hash[1:]}.bundle', 'Contents', 'Chapters'):
bundle = path.join(bundle, folder)
makedirs(bundle)
chmod(bundle, 0o755)
chown(bundle, plex_linux_user, plex_linux_group)
#put all thumbs in created folder
for index, thumb in enumerate(thumbs):
chapter_file = path.join(bundle, f'chapter{index+1}.jpg')
with open(chapter_file, 'wb') as f:
f.write(thumb)
chmod(chapter_file, 0o644)
chown(bundle, plex_linux_user, plex_linux_group)
return
def _reset(
type: str, data: dict, ssn, cursor, media_lib_id: str, watched_map: dict, timestamp_map: dict,
target_metadata: bool, target_poster: bool, target_art: bool
):
#reset different data based on the type
if type in media_types:
keys, media_type = media_types[type][:2]
else:
return 'Unknown source type when trying to reset data (internal error)'
#set all fields to unlocked in plex
rating_key = data['ratingKey']
payload = {
'type': media_type,
'id': rating_key
}
if type == 'collection':
for key in keys:
if key in metadata_skip_keys: continue
payload[f'{key}.locked'] = 0
else:
if target_poster == True:
payload['thumb.locked'] = 0
if target_art == True:
payload['art.locked'] = 0
if target_metadata == True:
for key in keys:
if key[0].isupper():
payload[f'{key.lower()}.locked'] = 0
else:
payload[f'{key}.locked'] = 0
ssn.put(f'{base_url}/library/sections/{media_lib_id}/all', params=payload)
return
def plex_exporter_importer(
verbose: bool, ssn, type: str, process: list, location: str,
all: bool, all_movie: bool=False, all_show: bool=False, all_music: bool=False,
library_name: str=None,
movie_name: str=None,
series_name: str=None, season_number: int=None, episode_number: int=None,
artist_name: str=None, album_name: str=None, track_name: str=None
):
result_json, watched_map, timestamp_map = [], {}, {}
lib_target_specifiers = (library_name,movie_name,series_name,season_number,episode_number,artist_name,album_name,track_name)
all_target_specifiers = (all_movie, all_show, all_music)
#check for illegal arg parsing
if not type in process_types:
return 'Invalid value for "type"'
if platform == False and type == 'import' and 'chapter_thumbnails' in process:
return 'Importing chapter thumbnails on a non-linux system is not supported'
#setup db location
if type == 'export':
if path.isdir(location):
database_file = f'{path.splitext(path.abspath(__file__))[0]}.db'
if path.isfile(database_file):
print(f'Exporting to {database_file} (Updating)')
else:
print(f'Exporting to {database_file}')
elif location.endswith('.db'):
database_file = location
if path.isfile(location):
print(f'Exporting to {database_file} (Updating)')
else: