forked from jeffski10/script.kcleaner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
default.py
2006 lines (1537 loc) · 73.5 KB
/
default.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
# ============================================================
# KCleaner - Version 4.0 by D. Lanik (2017)
# ------------------------------------------------------------
# Clean up Kodi
# ------------------------------------------------------------
# License: GPL (http://www.gnu.org/licenses/gpl-3.0.html)
# ============================================================
import xbmc
import xbmcgui
import xbmcvfs
import xbmcplugin
import xbmcaddon
import os
import shutil
import sqlite3
import json
import urllib.request, urllib.error, urllib.parse
import gzip
import sys
import codecs
import pickle
from distutils.util import strtobool
from xml.dom import minidom
# ============================================================
# Check Broken Sources
# ============================================================
def ProcessBrokenSources(iMode):
global booDebug
global strEndMessage
intCancel = 0
intObjects = 0
c = 0
strMess = __addon__.getLocalizedString(30019) # Scanning for repositories
strMess2 = __addon__.getLocalizedString(30012) # Checking paths...
if iMode:
progress = xbmcgui.DialogProgressBG()
else:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
sourcesS = ['pictures', 'music', 'video', 'files',]
Ppaths = []
intObjects += len(sourcesS)
intObjects += 0.1
for k in sourcesS:
# get paths from KODI sources
paths = getJson("Files.GetSources", "media", k, "sources")
percent = (c / len(sourcesS)) * 100
message1 = strMess + " " + k + "\n"
message2 = strMess2 + " " + str(int(c)) + " / " + str(int(intObjects))
progress.update(int(percent), str(message1) + str(message2))
c += 1
for i, jj in enumerate(paths[:]):
if jj["file"][:9] != "addons://" and jj["file"][:6] != "rss://" and jj["file"][:6] != "ftp://" \
and jj["file"][:7] != "sftp://" and jj["file"][:7] != "http://" and jj["file"][:10] != "videodb://" \
and jj["file"][:10] != "musicdb://" and jj["file"][:7] != "cdda://":
afg = xbmcvfs.translatePath(jj["file"])
if xbmcvfs.exists(afg):
xbmc.log("KCLEANER >> SOURCE PATHS (" + k +") >> " + afg + " >> ok")
else:
xbmc.log("KCLEANER >> SOURCE PATHS (" + k +") >> " + afg + " >> error")
mess1 = __addon__.getLocalizedString(30123) # CAN NOT BE FOUND
strEndMessage += "[SOURCE:" + k + "] " + afg + " [B][COLOR red]" + mess1 + "[/B][/COLOR]\n"
progress.close()
return intCancel
# ============================================================
# Define Sizes Class
# ============================================================
class Sizes():
def __init__(self, subcat, cat, size):
self.subcat = subcat
self.cat = cat
self.size = size
def __repr__(self):
return "%s %s %s" % (self.subcat, self.cat, self.size)
def __str__(self):
return "%s %s %s" % (self.subcat, self.cat, self.size)
# ============================================================
# Calculate how much space would be reclaimed
# ============================================================
def CalcDeleted():
global __addon__
global arr
global ignoreAniGifs
global ignore_existing_thumbs
global ignore_packages
TotalfileSize = 0.0
fileSize = 0.0
ignore_existing_thumbs = bool(strtobool(str(__addon__.getSetting('ignore_existing_thumbs').title())))
ignore_packages = int(__addon__.getSetting('ignore_packages'))
totSizeArr = []
for j, entry in enumerate(arr):
clear_cache_path = xbmcvfs.translatePath(entry[1])
if os.path.exists(clear_cache_path):
anigPath = os.path.join(clear_cache_path, "animatedgifs")
arccPath = os.path.join(xbmcvfs.translatePath("special://temp"), "archive_cache")
if entry[3] == 'thumbnails':
dataBase = os.path.join(xbmcvfs.translatePath("special://database/"), "Textures13.db")
conn = sqlite3.connect(dataBase)
c = conn.cursor()
if entry[3] == 'packages' and ignore_packages > 0:
plist = getPackages()
for root, dirs, files in os.walk(clear_cache_path):
if (root != anigPath and root != arccPath) or (root == anigPath and not ignoreAniGifs):
for f in files:
try:
fileSize = os.path.getsize(os.path.join(root, f))
except Exception:
fileSize = 0
if entry[3] == 'packages' and ignore_packages > 0:
if f in plist:
TotalfileSize += fileSize
elif entry[3] == 'thumbnails' and ignore_existing_thumbs and not fast_thumb_check:
thumbFolder = os.path.split(root)[1]
thumbPath = thumbFolder + "/" + f
sqlstr = "SELECT * FROM texture WHERE cachedurl=" + "'" + thumbPath + "'"
c.execute(sqlstr)
data = c.fetchone()
if not data:
TotalfileSize += fileSize
elif entry[3] == 'addons':
if not entry[4]:
TotalfileSize += fileSize
else:
TotalfileSize += fileSize
if entry[2]:
for d in dirs:
if os.path.join(root, d) != anigPath and os.path.join(root, d) != arccPath:
TotalfileSize += getFolderSize(os.path.join(root, d))
if entry[3] == 'thumbnails':
conn.close()
mess3 = " %0.2f " % ((TotalfileSize / (1048576.00000001)),)
mess = entry[0] + mess3
totSizeArr.append(Sizes(entry[0], entry[3], str(TotalfileSize)))
TotalfileSize = 0.0
addontot = 0.0
custtot = 0.0
atvtot = 0.0
totalsize = 0.0
msizes = []
for i, line in enumerate(totSizeArr):
if line.cat == 'addons':
addontot += float(line.size)
totalsize += addontot
elif line.cat == 'custom':
custtot += float(line.size)
totalsize += custtot
elif line.cat == 'atv':
atvtot += float(line.size)
totalsize += atvtot
else:
mess = " %0.2f " % ((float(line.size) / (1048576.00000001)),)
msizes.append([line.cat, mess])
totalsize += float(line.size)
mess = " %0.2f " % ((addontot / (1048576.00000001)),)
msizes.append(['addons', mess])
mess = " %0.2f " % ((custtot / (1048576.00000001)),)
msizes.append(['custom', mess])
mess = " %0.2f " % ((atvtot / (1048576.00000001)),)
msizes.append(['atv', mess])
TotalfileSize = 0 # get uninstalled addon data size
data_path = xbmcvfs.translatePath('special://profile/addon_data/')
installedAddons, countInstalledAddons = getLocalAddons()
addonData, intObjects = getLocalAddonDataFolders()
for d in addonData:
if d not in installedAddons:
fullName = os.path.join(data_path, d)
TotalfileSize += getFolderSize(fullName)
mess = " %0.2f " % ((TotalfileSize / (1048576.00000001)),)
msizes.append(['emptyaddon', mess])
totalsize += float(TotalfileSize)
mess = " %0.2f " % ((totalsize / (1048576.00000001)),)
msizes.append(['total', mess])
for i, line in enumerate(msizes):
xbmc.log("KCLEANER >> CALCULATED SAVINGS >> " + str(line))
return msizes
# ============================================================
# Change local path(s) in settings to special://
# ============================================================
def ProcessSpecial(iMode):
global strEndMessage
global __addon__
__addon__.setSetting('lock', 'true')
intCancel = 0
intObjects = 0
counter = 0
intTot = 0
strMess = __addon__.getLocalizedString(30118) # Checking paths to be compacted...
strMess2 = __addon__.getLocalizedString(30115) # Checking...
if iMode:
progress = xbmcgui.DialogProgressBG()
else:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
userDataPath = xbmcvfs.translatePath("special://userdata")
for root, dirs, files in os.walk(userDataPath):
for f in files:
if get_extension(f) == "xml":
intObjects += 1
intObjects += 0.1
for root, dirs, files in os.walk(userDataPath):
for f in files:
if get_extension(f) == "xml":
if get_filename(f) == "settings" or root == userDataPath:
p = os.path.join(root, f)
pout = os.path.join(root, f + "_NEW")
strMess = __addon__.getLocalizedString(30025) # Checking:
strMess2 = __addon__.getLocalizedString(30018) # Compacted:
percent = (counter / intObjects) * 100
message1 = strMess + str(f) + "\n"
message2 = strMess2 + str(int(counter)) + " / " + str(int(intObjects))
progress.update(int(percent), str(message1) + str(message2))
if not iMode:
try:
if progress.iscanceled():
intCancel = 1
break
except Exception:
pass
fp = codecs.open(p, "r", "utf-8")
if os.path.isfile(pout):
try:
os.remove(pout)
except Exception:
xbmc.log("KCLEANER >> COULDN'T DELETE OLD _NEW FILE")
fpout = codecs.open(pout, "w", "utf-8")
wasChanged = False
for line in fp:
if userDataPath in line:
newline = line.replace(userDataPath, "special://userdata/")
newline = newline.replace("\\", "/")
xbmc.log("KCLEANER >> COMPACTING PATH: " + root + "\\" + f)
wasChanged = True
else:
newline = line
fpout.write(newline)
fp.close()
fpout.close()
counter += 1
if wasChanged:
intTot += 1
try:
if os.path.isfile(p + "_ORIG"):
os.remove(p + "_ORIG")
os.rename(p, p + "_ORIG")
os.rename(pout, p)
pass
except Exception:
xbmc.log("KCLEANER >> COULDN'T DELETE OR RENAME ORIGINAL FILE")
else:
try:
os.remove(pout)
except Exception:
xbmc.log("KCLEANER >> COULDN'T DELETE NEW FILE")
if intTot > 0:
strMess = __addon__.getLocalizedString(30139) # Compacted settings paths:
strEndMessage = strMess + " " + str(intTot) + "\n"
else:
strEndMessage = __addon__.getLocalizedString(30139) + " " + __addon__.getLocalizedString(30153) + "\n" # Compacted settings paths: / # No paths compacted.
progress.close()
return intCancel, intTot
# ============================================================
# Clean texture database
# ============================================================
def CleanTextures(iMode):
global __addon__
global booDebug
global strEndMessage
__addon__.setSetting('lock', 'true')
intCancel = 0
intObjects = 0
counter = 0
strMess = __addon__.getLocalizedString(30114) # Scanning Textures database...
strMess2 = __addon__.getLocalizedString(30115) # Checking...
if iMode == 1:
progress = xbmcgui.DialogProgressBG()
progress.create(strMess, strMess2)
elif iMode == 0:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
dataBase = os.path.join(xbmcvfs.translatePath("special://database/"), "Textures13.db")
oldfileSize = os.path.getsize(dataBase)
conn = sqlite3.connect(dataBase)
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM texture")
intObjects = c.fetchone()[0]
intObjects += 0.1
try:
c.execute("SELECT * FROM texture")
data = c.fetchall()
except Exception as e:
xbmc.log("KCLEANER >> SQL ERROR IN Textures13: " + str(e))
data = None
for d in data:
recID = d[0]
textureName = d[2].replace('/', os.sep)
thumbPath = os.path.join(xbmcvfs.translatePath("special://thumbnails"), textureName)
fileName = xbmcvfs.translatePath(d[1])
strMess = __addon__.getLocalizedString(30116) # Checking record ID:
strMess2 = __addon__.getLocalizedString(30014) # Deleted:
percent = (counter / intObjects) * 100
message1 = strMess + str(recID) + "\n"
message2 = strMess2 + str(int(counter)) + " / " + str(int(intObjects))
if iMode < 2:
progress.update(int(percent), str(message1) + str(message2))
if iMode == 0:
try:
if progress.iscanceled():
intCancel = 1
break
except Exception:
pass
if not os.path.isfile(thumbPath):
try:
c.execute("DELETE FROM texture WHERE id=?", (recID,))
conn.commit()
c.execute("DELETE FROM sizes WHERE idtexture=?", (recID,))
conn.commit()
if booDebug:
xbmc.log("KCLEANER >> DELETED RECORD FROM DB: " + str(thumbPath))
counter += 1
except Exception as e:
xbmc.log("KCLEANER >> SQL ERROR IN Textures13 DELETING ID: " + str(recID) + " >> " + str(e))
if fileName.startswith("http://") or fileName.startswith("https://") or fileName.startswith("image://") or fileName.endswith("/transform?size=thumb"):
pass
else:
if not os.path.isfile(fileName):
try:
c.execute("DELETE FROM texture WHERE id=?", (recID,))
conn.commit()
c.execute("DELETE FROM sizes WHERE idtexture=?", (recID,))
conn.commit()
if booDebug:
xbmc.log("KCLEANER >> DELETED RECORD FROM DB: " + str(fileName))
counter += 1
except Exception as e:
xbmc.log("KCLEANER >> SQL ERROR IN Textures13 DELETING ID: " + str(recID) + " >> " + str(e))
conn.execute("VACUUM")
conn.close()
if counter > 0:
newfileSize = os.path.getsize(dataBase)
intTot = (oldfileSize - newfileSize) / 1048576.00000001
strSaved = '%0.2f' % (intTot,)
strMess = __addon__.getLocalizedString(30136) # Deleted
strMess2 = __addon__.getLocalizedString(30137) # stale records from Textures13.db database
strMess3 = __addon__.getLocalizedString(30112) # Mb
strEndMessage = strMess + " " + str(counter) + " " + strMess2 + " (" + strSaved + " " + strMess3 + ")\n"
else:
intTot = 0
strEndMessage += (__addon__.getLocalizedString(30099) + ": ") # Clean textures DB
strEndMessage += __addon__.getLocalizedString(30152) + "\n" # No records deleted
if iMode < 2:
progress.close()
return intCancel, intTot
# ============================================================
# Textbox class
# ============================================================
def TextBoxes(heading, anounce):
class TextBox():
"""Thanks to BSTRDMKR for this code:)"""
WINDOW = 10147
CONTROL_LABEL = 1
CONTROL_TEXTBOX = 5 # constants
def __init__(self, *args, **kwargs):
xbmc.executebuiltin("ActivateWindow(%d)" % (self.WINDOW,)) # activate the text viewer window
self.win = xbmcgui.Window(self.WINDOW) # get window
xbmc.sleep(500) # give window time to initialize
self.setControls()
def setControls(self):
self.win.getControl(self.CONTROL_LABEL).setLabel(heading) # set heading
try:
f = open(anounce)
text = f.read()
except Exception:
text = anounce
self.win.getControl(self.CONTROL_TEXTBOX).setText(text)
return
TextBox()
# ============================================================
# Get extension
# ============================================================
def get_extension(filename):
ext = os.path.splitext(filename)[1][1:].strip()
return ext
# ============================================================
# Get filename
# ============================================================
def get_filename(filename):
name = os.path.splitext(filename)[0].strip()
return name
# ============================================================
# Delete Cache
# ============================================================
def DeleteFiles(cleanIt, iMode):
global __addon__
global arr
global ignoreAniGifs
global ignore_existing_thumbs
global ignore_packages
global strEndMessage
global booDebug
__addon__.setSetting('lock', 'true')
intCancel = 0
intObjects = 0
count = 0
TotalfileSize = 0.0
fileSize = 0.0
intTot = 0
grandTotal = 0
ignore_existing_thumbs = bool(strtobool(str(__addon__.getSetting('ignore_existing_thumbs').title())))
ignore_packages = int(__addon__.getSetting('ignore_packages'))
for j, entry in enumerate(arr):
if entry[3] in cleanIt and not entry[4]:
clear_cache_path = xbmcvfs.translatePath(entry[1])
if os.path.exists(clear_cache_path):
for root, dirs, files in os.walk(clear_cache_path):
intObjects += len(files)
strMess = __addon__.getLocalizedString(30011) # Scanning for temporary files
strMess2 = __addon__.getLocalizedString(30012) # Checking paths...
if iMode == 1:
progress = xbmcgui.DialogProgressBG()
progress.create(strMess, strMess2)
elif iMode == 0:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
intObjects += 0.1
for j, entry in enumerate(arr):
if entry[3] in cleanIt and not entry[4]:
clear_cache_path = xbmcvfs.translatePath(entry[1])
if os.path.exists(clear_cache_path):
anigPath = os.path.join(clear_cache_path, "animatedgifs")
arccPath = os.path.join(xbmcvfs.translatePath("special://temp"), "archive_cache")
if entry[3] == 'thumbnails':
dataBase = os.path.join(xbmcvfs.translatePath("special://database/"), "Textures13.db")
conn = sqlite3.connect(dataBase)
c = conn.cursor()
if entry[3] == 'packages' and ignore_packages > 0:
plist = getPackages()
for root, dirs, files in os.walk(clear_cache_path):
if (root != anigPath and root != arccPath) or (root == anigPath and not ignoreAniGifs):
for f in files:
strMess = __addon__.getLocalizedString(30013) # Cleaning:
strMess2 = __addon__.getLocalizedString(30014) # Deleted:
percent = (count / intObjects) * 100
message1 = strMess + entry[0] + "\n"
message2 = strMess2 + str(int(count)) + " / " + str(int(intObjects))
if iMode < 2:
progress.update(int(percent), str(message1) + str(message2))
if iMode == 0:
try:
if progress.iscanceled():
intCancel = 1
break
except Exception:
pass
try:
fileSize = os.path.getsize(os.path.join(root, f))
except Exception:
fileSize = 0
if entry[3] == 'packages' and ignore_packages > 0:
if f in plist:
try:
os.unlink(os.path.join(root, f))
TotalfileSize += fileSize
if booDebug:
xbmc.log("KCLEANER >> DELETED >>" + f)
except Exception as e:
xbmc.log("KCLEANER >> CAN NOT DELETE FILE >>" + f + "<< ERROR: " + str(e))
count += 1
elif entry[3] == 'thumbnails' and ignore_existing_thumbs:
thumbFolder = os.path.split(root)[1]
thumbPath = thumbFolder + "/" + f
sqlstr = "SELECT * FROM texture WHERE cachedurl=" + "'" + thumbPath + "'"
c.execute(sqlstr)
data = c.fetchone()
if not data:
try:
os.unlink(os.path.join(root, f))
TotalfileSize += fileSize
if booDebug:
xbmc.log("KCLEANER >> DELETED >>" + f)
except Exception as e:
xbmc.log("KCLEANER >> CAN NOT DELETE FILE >>" + f + "<< ERROR: " + str(e))
count += 1
else:
try:
os.unlink(os.path.join(root, f))
TotalfileSize += fileSize
if booDebug:
xbmc.log("KCLEANER >> DELETED >>" + f)
except Exception as e:
xbmc.log("KCLEANER >> CAN NOT DELETE FILE >>" + f + "<< ERROR: " + str(e))
count += 1
if entry[2]:
for d in dirs:
if os.path.join(root, d) != anigPath and os.path.join(root, d) != arccPath:
try:
shutil.rmtree(os.path.join(root, d))
if booDebug:
xbmc.log("KCLEANER >> DELETED >>" + d)
except Exception as e:
xbmc.log("KCLEANER >> CAN NOT DELETE FOLDER >>" + d + "<< ERROR: " + str(e))
else:
pass
if entry[3] == 'thumbnails':
conn.close()
if TotalfileSize > 0:
mess1 = __addon__.getLocalizedString(30113) # cleaned:
mess2 = __addon__.getLocalizedString(30112) # Mb:
mess3 = " %0.2f " % ((TotalfileSize / (1048576.00000001)),)
mess = entry[3].title() + " (" + entry[0] + "): " + entry[0] + mess1 + mess3 + mess2
strEndMessage += (mess + "\n")
xbmc.log("KCLEANER >> CLEANING >> " + mess)
intTot = TotalfileSize / 1048576.00000001
grandTotal += TotalfileSize
else:
strEndMessage += (entry[3].title() + " (" + entry[0] + ") : ")
strEndMessage += __addon__.getLocalizedString(30150) + "\n" # No files deleted
TotalfileSize = 0.0
if iMode < 2:
progress.close()
return intCancel, intTot
# ============================================================
# Get All Packages
# ============================================================
def getPackages():
global ignore_packages
packAge = []
clear_cache_path = xbmcvfs.translatePath('special://home/addons/packages')
if os.path.exists(clear_cache_path):
for root, dirs, files in os.walk(clear_cache_path):
for e, f in enumerate(files):
name = os.path.splitext(f)[0]
version = name.rsplit('-', 1)
dt = os.path.getmtime(os.path.join(root, f))
packAge.append([version[0], version[1], dt, f])
uniquePackage = set()
for e, item in enumerate(packAge):
uniquePackage.add(packAge[e][0])
deletePackages = []
for item in uniquePackage:
strVers = []
for e, lst in enumerate(packAge):
if packAge[e][0] == item:
strVers.append(packAge[e])
strVers.sort(key=lambda date: packAge[e][2])
strVers.reverse()
for i, vv in enumerate(strVers):
if i >= ignore_packages:
deletePackages.append(vv[3])
return deletePackages
# ============================================================
# Compact DBs
# ============================================================
def CompactDatabases(iMode):
global __addon__
global strEndMessage
__addon__.setSetting('lock', 'true')
intCancel = 0
intObjects = 0
counter = 0
intTot = 0
GreatTotal = 0
strMess = __addon__.getLocalizedString(30016) # Scanning for databases
strMess2 = __addon__.getLocalizedString(30012) # Checking paths...
if iMode == 1:
progress = xbmcgui.DialogProgressBG()
progress.create(strMess, strMess2)
elif iMode == 0:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
dbPath = xbmcvfs.translatePath("special://database/")
intObjects = 0
if os.path.exists(dbPath):
files = ([f for f in os.listdir(dbPath) if f.endswith('.db') and os.path.isfile(os.path.join(dbPath, f))])
intObjects = len(files)
intObjects += 0.1
for f in files:
strMess = __addon__.getLocalizedString(30017) # Compacting:
strMess2 = __addon__.getLocalizedString(30018) # Compacted:
percent = (counter / intObjects) * 100
message1 = strMess + f + "\n"
message2 = strMess2 + str(int(counter)) + " / " + str(int(intObjects))
if iMode < 2:
progress.update(int(percent), str(message1) + str(message2))
if iMode == 0:
try:
if progress.iscanceled():
intCancel = 1
break
except Exception:
pass
fileSizeBefore = os.path.getsize(os.path.join(dbPath, f))
CompactDB(os.path.join(dbPath, f))
fileSizeAfter = os.path.getsize(os.path.join(dbPath, f))
xbmc.log("KCLEANER >> COMPACTED DATABASE >>" + f)
if fileSizeAfter != fileSizeBefore:
mess1 = __addon__.getLocalizedString(30110) # Database
mess2 = __addon__.getLocalizedString(30111) # compacted:
mess3 = " %0.2f " % (((fileSizeBefore - fileSizeAfter) / (1048576.00000001)),)
mess4 = __addon__.getLocalizedString(30112) # Mb
strEndMessage += mess1 + f + mess2 + mess3 + mess4 + "\n"
intTot += (fileSizeBefore - fileSizeAfter) / 1048576.00000001
GreatTotal += (fileSizeBefore - fileSizeAfter)
counter += 1
if iMode < 2:
progress.close()
if GreatTotal == 0:
intTot = 0
strEndMessage += __addon__.getLocalizedString(30151) + "\n" # No database compacted.
return intCancel, intTot
# ============================================================
# Compact DB
# ============================================================
def CompactDB(SQLiteFile):
conn = sqlite3.connect(SQLiteFile)
conn.execute("VACUUM")
conn.close()
# ============================================================
# Get list of repositories
# ============================================================
def getLocalRepos():
global booDebug
installedRepos = []
repos = getJson("Addons.GetAddons", "type", "xbmc.addon.repository", "addons")
for f in repos:
installedRepos.append(f["addonid"])
if booDebug:
xbmc.log("KCLEANER >> INSTALLED REPOS >>" + f["addonid"])
count = len(installedRepos)
return installedRepos, count
# ============================================================
# Get list of installed addons
# ============================================================
def getLocalAddons():
global booDebug
installedAddons = []
addons = getJson("Addons.GetAddons", "type", "unknown", "addons")
for f in addons:
if f["type"] != "xbmc.addon.repository":
installedAddons.append(f["addonid"])
if booDebug:
xbmc.log("KCLEANER >> INSTALLED ADDONS >>" + f["addonid"])
count = len(installedAddons)
return installedAddons, count
# ============================================================
# Get list of addon data folders
# ============================================================
def getLocalAddonDataFolders():
addonData = []
data_path = xbmcvfs.translatePath('special://profile/addon_data/')
for item in os.listdir(data_path):
if os.path.isdir(os.path.join(data_path, item)):
addonData.append(item)
count = len(addonData)
return addonData, count
# ============================================================
# Delete data folders for nonexistant (uninstalled) addons
# ============================================================
def deleteAddonData(iMode):
global __addon__
global strEndMessage
__addon__.setSetting('lock', 'true')
intCancel = 0
counter = 0
TotalfileSize = 0
deleted = 0
strMess = __addon__.getLocalizedString(30117) # Checking unused data folders
strMess2 = __addon__.getLocalizedString(30012) # Checking paths...
if iMode == 1:
progress = xbmcgui.DialogProgressBG()
progress.create(strMess, strMess2)
elif iMode == 0:
progress = xbmcgui.DialogProgress()
progress.create(strMess, strMess2)
data_path = xbmcvfs.translatePath('special://profile/addon_data/')
installedAddons, countInstalledAddons = getLocalAddons()
addonData, intObjects = getLocalAddonDataFolders()
intObjects += 0.1
for d in addonData:
strMess = __addon__.getLocalizedString(30025) # Checking:
strMess2 = __addon__.getLocalizedString(30014) # Deleted:
percent = (counter / intObjects) * 100
message1 = strMess + str(d) + "\n"
message2 = strMess2 + str(int(deleted)) + " / " + str(int(intObjects))
if iMode < 2:
progress.update(int(percent), str(message1) + str(message2))
if iMode == 0:
try:
if progress.iscanceled():
intCancel = 1
break
except Exception:
pass
if d not in installedAddons:
fullName = os.path.join(data_path, d)
TotalfileSize += getFolderSize(fullName)
try:
shutil.rmtree(fullName)
xbmc.log("KCLEANER >> DELETING UNUSED ADDON DATA FOLDER >>" + fullName)
deleted += 1
except Exception as e:
xbmc.log("KCLEANER >> ERROR DELETING UNUSED ADDON DATA FOLDER: " + str(e))
counter += 1
if TotalfileSize > 0:
mess1 = __addon__.getLocalizedString(30113) # cleaned:
mess2 = __addon__.getLocalizedString(30112) # Mb:
mess3 = " %0.2f " % ((TotalfileSize / (1048576.00000001)),)
mess = __addon__.getLocalizedString(30100) + mess1 + mess3 + mess2 # Unused addon data folders
strEndMessage += (mess + "\n")
else:
strEndMessage += (__addon__.getLocalizedString(30100) + ": ") # Unused addon data folders
strEndMessage += __addon__.getLocalizedString(30150) + "\n" # No files deleted
if iMode < 2:
progress.close()
return intCancel, (TotalfileSize / 1048576.00000001)
# ============================================================
# Get folder size
# ============================================================
def getFolderSize(folder):
total_size = os.path.getsize(folder)
for item in os.listdir(folder):
itempath = os.path.join(folder, item)
if os.path.isfile(itempath):
total_size += os.path.getsize(itempath)
elif os.path.isdir(itempath):
total_size += getFolderSize(itempath)
return total_size
# ============================================================
# Get Kodi data by json
# ============================================================
def getJson(method, param1, param2, retname):
command = '''{
"jsonrpc": "2.0",
"id": 1,
"method": "%s",
"params": {
"%s": "%s"
}
}'''
result = xbmc.executeJSONRPC(command % (method, param1, param2))
py = json.loads(result)
if 'result' in py and retname in py['result']:
a = py['result'][retname]
if booDebug:
xbmc.log("KCLEANER >> READ SYSTEM SETTING >> " + method + ":" + param1 + "."+ param2 + " >> " + str(a) )
return a
else:
return ""
# ============================================================
# Check Addons
# ============================================================