forked from Nandaka/PixivUtil2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PixivDBManager.py
1491 lines (1367 loc) · 56.6 KB
/
PixivDBManager.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
#!C:/Python37-32/python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sqlite3
import sys
from datetime import datetime
# import colorama
from colorama import Back, Fore, Style
import PixivHelper
from PixivListItem import PixivListItem
script_path = PixivHelper.module_path()
class PixivDBManager(object):
"""Pixiv Database Manager"""
rootDirectory = "."
def __init__(self, root_directory, target='', timeout=5 * 60):
if target is None or len(target) == 0:
target = script_path + os.sep + "db.sqlite"
PixivHelper.print_and_log(
'info', "Using default DB Path: " + target)
else:
PixivHelper.print_and_log(
'info', "Using custom DB Path: " + target)
self.rootDirectory = root_directory
self.conn = sqlite3.connect(target, timeout)
def close(self):
self.conn.close()
##########################################
# I. Create/Drop Database #
##########################################
def createDatabase(self):
print('Creating database...', end=' ')
try:
c = self.conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_master_member (
member_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
name TEXT,
save_folder TEXT,
created_date DATE,
last_update_date DATE,
last_image INTEGER
)''')
self.conn.commit()
# add column isDeleted
# 0 = false, 1 = true
try:
c.execute(
'''ALTER TABLE pixiv_master_member ADD COLUMN is_deleted INTEGER DEFAULT 0''')
self.conn.commit()
except BaseException:
pass
# add column for artist token
try:
c.execute(
'''ALTER TABLE pixiv_master_member ADD COLUMN member_token TEXT''')
self.conn.commit()
except BaseException:
pass
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_master_image (
image_id INTEGER PRIMARY KEY,
member_id INTEGER,
title TEXT,
save_name TEXT,
created_date DATE,
last_update_date DATE
)''')
# add column isManga
try:
c.execute(
'''ALTER TABLE pixiv_master_image ADD COLUMN is_manga TEXT''')
except BaseException:
pass
c.execute('''CREATE TABLE IF NOT EXISTS pixiv_manga_image (
image_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (image_id, page)
)''')
self.conn.commit()
# FANBOX
c.execute('''CREATE TABLE IF NOT EXISTS fanbox_master_post (
member_id INTEGER,
post_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
title TEXT,
fee_required INTEGER,
published_date DATE,
updated_date DATE,
post_type TEXT,
last_update_date DATE
)''')
c.execute('''CREATE TABLE IF NOT EXISTS fanbox_post_image (
post_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (post_id, page)
)''')
self.conn.commit()
# Sketch
c.execute('''CREATE TABLE IF NOT EXISTS sketch_master_post (
member_id INTEGER,
post_id INTEGER PRIMARY KEY ON CONFLICT IGNORE,
title TEXT,
published_date DATE,
updated_date DATE,
post_type TEXT,
last_update_date DATE
)''')
c.execute('''CREATE TABLE IF NOT EXISTS sketch_post_image (
post_id INTEGER,
page INTEGER,
save_name TEXT,
created_date DATE,
last_update_date DATE,
PRIMARY KEY (post_id, page)
)''')
# Novel
self.create_update_novel_table(c)
self.conn.commit()
print('done.')
except BaseException:
print('Error at createDatabase():', str(sys.exc_info()))
print('failed.')
raise
finally:
c.close()
def dropDatabase(self):
try:
c = self.conn.cursor()
c.execute('''DROP TABLE IF EXISTS pixiv_master_member''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS pixiv_master_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS pixiv_manga_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS fanbox_master_post''')
c.execute('''DROP TABLE IF EXISTS fanbox_post_image''')
self.conn.commit()
c.execute('''DROP TABLE IF EXISTS sketch_master_post''')
c.execute('''DROP TABLE IF EXISTS sketch_post_image''')
self.conn.commit()
except BaseException:
print('Error at dropDatabase():', str(sys.exc_info()))
print('failed.')
raise
finally:
c.close()
print('done.')
def compactDatabase(self):
print('Compacting Database, this might take a while...')
try:
c = self.conn.cursor()
c.execute('''VACUUM''')
self.conn.commit()
except BaseException:
print('Error at compactDatabase():', str(sys.exc_info()))
raise
finally:
c.close()
print('done.')
##########################################
# II. Export/Import DB #
##########################################
def importList(self, listTxt):
print('Importing list...', end=' ')
print('Found', len(listTxt), 'items', end=' ')
try:
c = self.conn.cursor()
for item in listTxt:
c.execute('''INSERT OR IGNORE INTO pixiv_master_member VALUES(?, ?, ?, datetime('now'), '1-1-1', -1, 0, '')''',
(item.memberId, str(item.memberId), r'N\A'))
c.execute('''UPDATE pixiv_master_member
SET save_folder = ?
WHERE member_id = ? ''',
(item.path, item.memberId))
self.conn.commit()
except BaseException:
print('Error at importList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
return 0
def exportImageTable(self, name):
print(f'Exporting {name} table ...', end=' ')
im_list = list()
if name == "Pixiv":
table = "pixiv_master_image"
key = "image_id"
elif name == "Fanbox":
table = "fanbox_master_post"
key = "post_id"
elif name == "Sketch":
table = "sketch_master_post"
key = "post_id"
else:
raise
try:
c = self.conn.cursor()
c.execute(f''' SELECT COUNT(*) FROM {table}''')
result = c.fetchall()
if result[0][0] > 10000:
print('Row count is more than 10000 (actual row count:',
str(result[0][0]), ')')
print('It may take a while to retrieve the data.')
arg = input('Continue [y/n, default is yes]').rstrip("\r") or 'y'
answer = arg.lower()
if answer not in ('y', 'n', 'o'):
PixivHelper.print_and_log("error", f"Invalid args for TODO: {arg}, valid values are [y/n/o].")
return
if answer == 'y':
c = self.conn.cursor()
c.execute(f'''SELECT {key}
FROM {table}
ORDER BY member_id''')
for row in c:
im_list.append(row[0])
else:
c.execute(f'''SELECT {key}
FROM {table}
ORDER BY member_id''')
for row in c:
im_list.append(row[0])
c.close()
print('done.')
return im_list
except BaseException:
print('Error at exportImageTable():', str(sys.exc_info()))
print('failed')
raise
def exportList(self, filename, include_artist_token=True):
print('Exporting list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT member_id, save_folder, name, member_token
FROM pixiv_master_member
WHERE is_deleted = 0
ORDER BY member_id''')
if not filename.endswith(".txt"):
filename = filename + '.txt'
writer = codecs.open(filename, 'wb', encoding='utf-8')
writer.write('###Export date: {0} ###\r\n'.format(datetime.today()))
for row in c:
if include_artist_token:
data = row[2]
token = row[3]
writer.write(f"# name: {data},token: {token}")
writer.write("\r\n")
writer.write(str(row[0]))
if len(row[1]) > 0:
writer.write(' ' + str(row[1]))
writer.write('\r\n')
writer.write('###END-OF-FILE###')
except BaseException:
print('Error at exportList():', str(sys.exc_info()))
print('failed')
raise
finally:
if writer is not None:
writer.close()
c.close()
print('done.')
def exportDetailedList(self, filename):
print('Exporting detailed list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM pixiv_master_member
WHERE is_deleted = 0
ORDER BY member_id''')
filename = filename + '.csv'
writer = codecs.open(filename, 'wb', encoding='utf-8')
writer.write('member_id,name,save_folder,created_date,last_update_date,last_image,is_deleted,member_token\r\n')
for row in c:
for string in row:
# Unicode write!!
data = string
writer.write(data)
writer.write(',')
writer.write('\r\n')
writer.write('###END-OF-FILE###')
writer.close()
except BaseException:
print('Error at exportDetailedList(): ' + str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
def exportFanboxPostList(self, filename, sep=","):
print('Exporting FANBOX post list...', end=' ')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM fanbox_master_post
ORDER BY member_id, post_id''')
filename = filename + '.csv'
writer = codecs.open(filename, 'wb', encoding='utf-8')
columns = ['member_id', 'post_id', 'title', 'fee_required', 'published_date', 'update_date', 'post_type', 'last_update_date']
writer.write(sep.join(columns))
writer.write('\r\n')
for row in c:
writer.write(sep.join([str(x) for x in row]))
writer.write('\r\n')
writer.write('###END-OF-FILE###')
writer.close()
except BaseException:
print('Error at exportFanboxPostList(): ' + str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
##########################################
# III. Print DB #
##########################################
def printMemberList(self, isDeleted=False):
print('Printing member list:')
try:
c = self.conn.cursor()
c.execute('''SELECT * FROM pixiv_master_member
WHERE is_deleted = ? ORDER BY member_id''', (int(isDeleted), ))
print('%10s %25s %25s %20s %20s %10s %s %s' % ('member_id',
'name',
'save_folder',
'created_date',
'last_update_date',
'last_image',
'is_deleted',
'member_token'))
i = 0
for row in c:
print('%10d %#25s %#25s %20s %20s %10d %5s' %
(row[0], row[1].strip(), row[2], row[3], row[4], row[5], row[6]))
i = i + 1
if i == 79:
select = input('Continue [y/n, default is yes]? ').rstrip("\r")
if select == 'n':
break
else:
print(
'member_id\tname\tsave_folder\tcreated_date\tlast_update_date\tlast_image')
i = 0
except BaseException:
print('Error at printMemberList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
def printImageList(self):
print('Printing image list:')
try:
c = self.conn.cursor()
c.execute(''' SELECT COUNT(*) FROM pixiv_master_image''')
result = c.fetchall()
if result[0][0] > 10000:
print('Row count is more than 10000 (actual row count:',
str(result[0][0]), ')')
print('It may take a while to retrieve the data.')
answer = input('Continue [y/n, default is no]').rstrip("\r")
if answer == 'y':
c.execute('''SELECT * FROM pixiv_master_image
ORDER BY member_id''')
print('')
for row in c:
for string in row:
print(' ', end=' ')
print(string)
print('')
else:
return
# Yavos: it seems you forgot something ;P
else:
c.execute(
'''SELECT * FROM pixiv_master_image ORDER BY member_id''')
print('')
for row in c:
for string in row:
print(' ', end=' ')
print(string)
print('')
# Yavos: end of change
except BaseException:
print('Error at printImageList():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
print('done.')
##########################################
# IV. CRUD Member Table #
##########################################
def insertNewMember(self, member_id=0, member_token=None):
try:
c = self.conn.cursor()
if member_id == 0:
while True:
temp = input('Member ID: ').rstrip("\r")
try:
member_id = int(temp)
except BaseException:
pass
if member_id > 0:
break
c.execute('''INSERT OR IGNORE INTO pixiv_master_member VALUES(?, ?, ?, datetime('now'), '1-1-1', -1, 0, ?)''',
(member_id, str(member_id), r'N\A', member_token))
self.conn.commit()
except BaseException:
print('Error at insertNewMember():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectAllMember(self, isDeleted=False):
members = list()
try:
c = self.conn.cursor()
c.execute('''SELECT member_id, save_folder FROM pixiv_master_member WHERE is_deleted = ? ORDER BY member_id''',
(int(isDeleted), ))
result = c.fetchall()
for row in result:
item = PixivListItem(row[0], row[1])
members.append(item)
except BaseException:
print('Error at selectAllMember():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
return members
def selectMembersByLastDownloadDate(self, difference):
members = list()
try:
c = self.conn.cursor()
try:
int_diff = int(difference)
except ValueError:
int_diff = 7
c.execute('''SELECT member_id, save_folder, (julianday(Date('now')) - julianday(last_update_date)) as diff
FROM pixiv_master_member
WHERE is_deleted <> 1 AND ( last_update_date == '1-1-1' OR diff > ? ) ORDER BY member_id''', (int_diff, ))
result = c.fetchall()
for row in result:
item = PixivListItem(row[0], row[1])
members.append(item)
except BaseException:
print('Error at selectMembersByLastDownloadDate():',
str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
return members
def selectMemberByMemberId(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_master_member WHERE member_id = ? ''', (member_id, ))
return c.fetchone()
except BaseException:
print('Error at selectMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectMemberByMemberId2(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT member_id, save_folder FROM pixiv_master_member WHERE member_id = ? ''', (member_id, ))
row = c.fetchone()
if row is not None:
return PixivListItem(row[0], row[1])
else:
return PixivListItem(int(member_id), '')
except BaseException:
print('Error at selectMemberByMemberId2():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def printMembersByLastDownloadDate(self, difference):
rows = self.selectMembersByLastDownloadDate(difference)
for row in rows:
for string in row:
print(' ', end=' ')
print(string)
print('\n')
def updateMemberName(self, memberId, memberName, member_token):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET name = ?, member_token = ?
WHERE member_id = ?
''', (memberName, member_token, memberId))
self.conn.commit()
except BaseException:
print('Error at updateMemberName():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateSaveFolder(self, memberId, saveFolder):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET save_folder = ?
WHERE member_id = ?
''', (saveFolder, memberId))
self.conn.commit()
except BaseException:
print('Error at updateSaveFolder():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateLastDownloadedImage(self, memberId, imageId):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET last_image = ?, last_update_date = datetime('now')
WHERE member_id = ?''', (imageId, memberId))
self.conn.commit()
except BaseException:
print('Error at updateLastDownloadedImage:', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateLastDownloadDate(self, memberId):
try:
c = self.conn.cursor()
c.execute("""UPDATE pixiv_master_member
SET last_update_date = datetime('now')
WHERE member_id = ?""", (memberId,))
self.conn.commit()
except BaseException:
print('Error at updateLastDownloadDate():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteMemberByMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (memberId, ))
self.conn.commit()
except BaseException:
print('Error at deleteMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteCascadeMemberByMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_manga_image
WHERE EXISTS (SELECT * FROM pixiv_master_image WHERE member_id = ?)''', (memberId, ))
c.execute('''DELETE FROM pixiv_master_image
WHERE member_id = ?''', (memberId, ))
c.execute('''DELETE FROM pixiv_master_member
WHERE member_id = ?''', (memberId, ))
self.conn.commit()
except BaseException:
print('Error at deleteCascadeMemberByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def setIsDeletedFlagForMemberId(self, memberId):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_member
SET is_deleted = 1, last_update_date = datetime('now')
WHERE member_id = ?''', (memberId,))
self.conn.commit()
except BaseException:
print('Error at setIsDeletedFlagForMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
##########################################
# V. CRUD Image Table #
##########################################
def insertImage(self, member_id, image_id, isManga=""):
try:
c = self.conn.cursor()
member_id = int(member_id)
image_id = int(image_id)
c.execute('''INSERT OR IGNORE INTO pixiv_master_image VALUES(?, ?, 'N/A' ,'N/A' , datetime('now'), datetime('now'), ? )''',
(image_id, member_id, isManga))
self.conn.commit()
except BaseException:
print('Error at insertImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertMangaImages(self, manga_files):
try:
c = self.conn.cursor()
c.executemany('''INSERT OR IGNORE INTO pixiv_manga_image
VALUES(?, ?, ?, datetime('now'), datetime('now'))''', manga_files)
self.conn.commit()
except BaseException:
print('Error at insertMangaImages():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def blacklistImage(self, memberId, ImageId):
try:
c = self.conn.cursor()
c.execute('''INSERT OR REPLACE INTO pixiv_master_image
VALUES(?, ?, '**BLACKLISTED**' ,'**BLACKLISTED**' , datetime('now'), datetime('now') )''',
(ImageId, memberId))
self.conn.commit()
except BaseException:
print('Error at blacklistImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByMemberId(self, member_id):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_master_image WHERE member_id = ? ''', (member_id,))
return c.fetchall()
except BaseException:
print('Error at selectImageByMemberId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByMemberIdAndImageId(self, member_id, image_id):
try:
c = self.conn.cursor()
c.execute('''SELECT image_id FROM pixiv_master_image
WHERE image_id = ? AND save_name != 'N/A' AND member_id = ?''', (image_id, member_id))
return c.fetchone()
except BaseException:
print('Error at selectImageByMemberIdAndImageId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByImageId(self, image_id, cols='*'):
try:
c = self.conn.cursor()
c.execute(
'''SELECT %s FROM pixiv_master_image WHERE image_id = ? AND save_name != 'N/A' ''' % (cols,), (image_id,))
return c.fetchone()
except BaseException:
print('Error at selectImageByImageId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectImageByImageIdAndPage(self, imageId, page):
try:
c = self.conn.cursor()
c.execute(
'''SELECT * FROM pixiv_manga_image WHERE image_id = ? AND page = ? ''', (imageId, page))
return c.fetchone()
except BaseException:
print('Error at selectImageByImageIdAndPage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updateImage(self, imageId, title, filename, isManga=""):
try:
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_image
SET title = ?, save_name = ?, last_update_date = datetime('now'), is_manga = ?
WHERE image_id = ?''', (title, filename, isManga, imageId))
self.conn.commit()
except BaseException:
print('Error at updateImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteImage(self, imageId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM pixiv_master_image WHERE image_id = ?''', (imageId, ))
c.execute('''DELETE FROM pixiv_manga_image WHERE image_id = ?''', (imageId, ))
self.conn.commit()
except BaseException:
print('Error at deleteImage():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def deleteSketch(self, postId):
try:
c = self.conn.cursor()
c.execute('''DELETE FROM sketch_master_post WHERE post_id = ?''', (postId, ))
c.execute('''DELETE FROM sketch_post_image WHERE post_id = ?''', (postId, ))
self.conn.commit()
except BaseException:
print('Error at deleteSketch():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def checkFilenames(self, base_filename, exts):
for ext2 in exts:
check_name = base_filename + ext2
if os.path.exists(check_name):
return True
return False
def cleanupFileExists(self, filename):
''' check if file or converted file exists '''
anim_ext = ['.zip', '.gif', '.apng', '.ugoira', '.webm']
fileExists = False
if filename is not None or len(filename) > 0:
if os.path.exists(filename):
return True
for ext in anim_ext:
# check filename in db against all combination possible filename in disk
if filename.endswith(ext):
base_filename = filename.rsplit(ext, 1)[0]
if self.checkFilenames(base_filename, anim_ext):
fileExists = True
break
return fileExists
def cleanUp(self):
anim_ext = ['.zip', '.gif', '.apng', '.ugoira', '.webm']
try:
print("Start clean-up operation.")
print("Selecting all images, this may take some times.")
c = self.conn.cursor()
c.execute('''SELECT image_id, save_name from pixiv_master_image''')
print("Checking images.")
for row in c:
# Issue 340
filename = row[1]
fileExists = False
if filename is not None and len(filename) > 0:
if os.path.exists(filename):
continue
for ext in anim_ext:
# check filename in db against all combination possible filename in disk
if filename.endswith(ext):
base_filename = filename.rsplit(ext, 1)[0]
if self.checkFilenames(base_filename, anim_ext):
fileExists = True
break
if not fileExists:
print("Missing: {0} at {1}".format(row[0], row[1]))
self.deleteImage(row[0])
self.conn.commit()
except BaseException:
print('Error at cleanUp():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def interactiveCleanUp(self):
items = []
try:
print("Start clean-up operation.")
print("Selecting all images, this may take some times.")
c = self.conn.cursor()
print("Collecting missing images.")
c.execute('''SELECT image_id, save_name from pixiv_master_image''')
for row in c:
# Issue 340
filename = row[1]
fileExists = self.cleanupFileExists(filename)
if not fileExists:
items.append(row)
print("Missing: {0} at \n{1}".format(row[0], row[1]))
while len(items) != 0:
# End scan
print(items)
regex = input(
"Please provide a search regex, use empty string to skip(Empty to stop now):").rstrip("\r")
if regex == "":
break
repl = input("Replace regex with what?").rstrip("\r")
regex = re.compile(regex)
# Replace any paths where replacement results in a correct path
ll = []
for row in items:
new_name = regex.sub(repl, row[1])
if self.cleanupFileExists(filename):
c.execute('''UPDATE pixiv_master_image
SET save_name = ?
WHERE id = ?''', (new_name, row[0]))
else:
ll.append(items)
items = ll
c.close()
self.conn.commit()
except BaseException:
print('Error at interactiveCleanUp():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
# TODO check mangaimage
# TODO check for files which exist but don't have a DB entry
def replaceRootPath(self):
oldPath = input("Old Path to Replace = ").rstrip("\r")
print("Replacing " + oldPath + " to " + self.rootDirectory)
cont = input("continue[y/n, default is no]?").rstrip("\r") or 'n'
if cont != "y":
print("Aborted")
return
try:
print("Start replace Root Path operation.")
print("Updating images, this may take some times.")
c = self.conn.cursor()
c.execute('''UPDATE pixiv_master_image
SET save_name = replace(save_name, ?, ?)
WHERE save_name like ?''', (oldPath, self.rootDirectory, oldPath + "%", ))
print("Updated image:", c.rowcount)
print("Updating manga images, this may take some times.")
c = self.conn.cursor()
c.execute('''UPDATE pixiv_manga_image
SET save_name = replace(save_name, ?, ?)
WHERE save_name like ?''', (oldPath, self.rootDirectory, oldPath + "%", ))
print("Updated manga image:", c.rowcount)
print("Updating FANBOX post images, this may take some times.")
c = self.conn.cursor()
c.execute('''UPDATE fanbox_post_image
SET save_name = replace(save_name, ?, ?)
WHERE save_name like ?''', (oldPath, self.rootDirectory, oldPath + "%", ))
print("Updated FANBOX post image:", c.rowcount)
print("Done")
except BaseException:
print('Error at replaceRootPath():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
##########################################
# VI. CRUD FANBOX post/image table #
##########################################
def insertPost(self, member_id, post_id, title, fee_required, published_date, post_type):
try:
c = self.conn.cursor()
post_id = int(post_id)
c.execute(
'''INSERT OR IGNORE INTO fanbox_master_post (member_id, post_id) VALUES(?, ?)''',
(member_id, post_id))
c.execute(
'''UPDATE fanbox_master_post SET title = ?, fee_required = ?, published_date = ?,
post_type = ?, last_update_date = datetime('now') WHERE post_id = ?''',
(title, fee_required, published_date, post_type, post_id))
self.conn.commit()
except BaseException:
print('Error at insertPost():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def insertPostImages(self, post_files):
try:
c = self.conn.cursor()
c.executemany('''INSERT OR REPLACE INTO fanbox_post_image
VALUES(?, ?, ?, datetime('now'), datetime('now'))''', post_files)
self.conn.commit()
except BaseException:
print('Error at insertPostImages():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def selectPostByPostId(self, post_id):
try:
c = self.conn.cursor()
post_id = int(post_id)
c.execute(
'''SELECT * FROM fanbox_master_post WHERE post_id = ?''',
(post_id,))
return c.fetchone()
except BaseException:
print('Error at selectPostByPostId():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()
def updatePostUpdateDate(self, post_id, updated_date):
try:
c = self.conn.cursor()
post_id = int(post_id)
c.execute(
'''UPDATE fanbox_master_post SET updated_date = ?
WHERE post_id = ?''',
(updated_date, post_id))
self.conn.commit()
except BaseException:
print('Error at updatePostUpdateDate():', str(sys.exc_info()))
print('failed')
raise
finally:
c.close()