-
Notifications
You must be signed in to change notification settings - Fork 125
/
__init__.py
2423 lines (1972 loc) · 85.2 KB
/
__init__.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
"""
Copyright 2022 Sketchfab
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import urllib
import requests
import threading
import time
from collections import OrderedDict
import subprocess
import tempfile
import json
import shutil
from uuid import UUID
import bpy
import bpy.utils.previews
from bpy.props import (StringProperty,
EnumProperty,
BoolProperty,
IntProperty,
PointerProperty)
bl_info = {
'name': 'Sketchfab Plugin',
'description': 'Browse and download free Sketchfab downloadable models',
'author': 'Sketchfab',
'license': 'APACHE2',
'deps': '',
'version': (1, 6, 1),
"blender": (2, 80, 0),
'location': 'View3D > Tools > Sketchfab',
'warning': '',
'wiki_url': 'https://github.com/sketchfab/blender-plugin/releases',
'tracker_url': 'https://github.com/sketchfab/blender-plugin/issues',
'link': 'https://github.com/sketchfab/blender-plugin',
'support': 'COMMUNITY',
'category': 'Import-Export'
}
bl_info['blender'] = getattr(bpy.app, "version")
PLUGIN_VERSION = str(bl_info['version']).strip('() ').replace(',', '.')
preview_collection = {}
thumbnailsProgress = set([])
ongoingSearches = set([])
is_plugin_enabled = False
class Config:
ADDON_NAME = 'io_sketchfab'
GITHUB_REPOSITORY_URL = 'https://github.com/sketchfab/blender-plugin'
GITHUB_REPOSITORY_API_URL = 'https://api.github.com/repos/sketchfab/blender-plugin'
SKETCHFAB_REPORT_URL = 'https://help.sketchfab.com/hc/en-us/requests/new?type=exporters&subject=Blender+Plugin'
SKETCHFAB_URL = 'https://sketchfab.com'
CLIENTID = 'hGC7unF4BHyEB0s7Orz5E1mBd3LluEG0ILBiZvF9'
SKETCHFAB_OAUTH = SKETCHFAB_URL + '/oauth2/token/'
SKETCHFAB_API = 'https://api.sketchfab.com'
SKETCHFAB_SEARCH = SKETCHFAB_API + '/v3/search'
SKETCHFAB_MODEL = SKETCHFAB_API + '/v3/models'
SKETCHFAB_ORGS = SKETCHFAB_API + '/v3/orgs'
SKETCHFAB_SIGNUP = 'https://sketchfab.com/signup'
BASE_SEARCH = SKETCHFAB_SEARCH + '?type=models&downloadable=true'
DEFAULT_FLAGS = '&staffpicked=true&sort_by=-staffpickedAt'
DEFAULT_SEARCH = SKETCHFAB_SEARCH + \
'?type=models&downloadable=true' + DEFAULT_FLAGS
SKETCHFAB_ME = '{}/v3/me'.format(SKETCHFAB_API)
BASE_SEARCH_OWN_MODELS = SKETCHFAB_ME + '/search?type=models&downloadable=true'
PURCHASED_MODELS = SKETCHFAB_ME + "/models/purchases?type=models"
SKETCHFAB_PLUGIN_VERSION = '{}/releases'.format(GITHUB_REPOSITORY_API_URL)
# Those will be set during plugin initialization, or upon setting a new cache directory
SKETCHFAB_TEMP_DIR = ""
SKETCHFAB_THUMB_DIR = ""
SKETCHFAB_MODEL_DIR = ""
SKETCHFAB_CATEGORIES = (('ALL', 'All categories', 'All categories'),
('animals-pets', 'Animals & Pets', 'Animals and Pets'),
('architecture', 'Architecture', 'Architecture'),
('art-abstract', 'Art & Abstract', 'Art & Abstract'),
('cars-vehicles', 'Cars & vehicles', 'Cars & vehicles'),
('characters-creatures', 'Characters & Creatures', 'Characters & Creatures'),
('cultural-heritage-history', 'Cultural Heritage & History', 'Cultural Heritage & History'),
('electronics-gadgets', 'Electronics & Gadgets', 'Electronics & Gadgets'),
('fashion-style', 'Fashion & Style', 'Fashion & Style'),
('food-drink', 'Food & Drink', 'Food & Drink'),
('furniture-home', 'Furniture & Home', 'Furniture & Home'),
('music', 'Music', 'Music'),
('nature-plants', 'Nature & Plants', 'Nature & Plants'),
('news-politics', 'News & Politics', 'News & Politics'),
('people', 'People', 'People'),
('places-travel', 'Places & Travel', 'Places & Travel'),
('science-technology', 'Science & Technology', 'Science & Technology'),
('sports-fitness', 'Sports & Fitness', 'Sports & Fitness'),
('weapons-military', 'Weapons & Military', 'Weapons & Military'))
SKETCHFAB_FACECOUNT = (('ANY', "All", ""),
('10K', "Up to 10k", ""),
('50K', "10k to 50k", ""),
('100K', "50k to 100k", ""),
('250K', "100k to 250k", ""),
('250KP', "250k +", ""))
SKETCHFAB_SORT_BY = (('RELEVANCE', "Relevance", ""),
('LIKES', "Likes", ""),
('VIEWS', "Views", ""),
('RECENT', "Recent", ""))
SKETCHFAB_SEARCH_DOMAIN = (('DEFAULT', "All site", "", 0),
('OWN', "Own Models (PRO)", "", 1),
('STORE', "Store purchases", "", 2))
MAX_THUMBNAIL_HEIGHT = 256
SKETCHFAB_UPLOAD_LIMITS = {
"basic" : 100 * 1024 * 1024,
"pro": 200 * 1024 * 1024,
"prem": 500 * 1024 * 1024,
"ent": 500 * 1024 * 1024
}
class Utils:
def humanify_size(size):
suffix = 'B'
readable = size
# Megabyte
if size > 1048576:
suffix = 'MB'
readable = size / 1048576.0
# Kilobyte
elif size > 1024:
suffix = 'KB'
readable = size / 1024.0
readable = round(readable, 2)
return '{}{}'.format(readable, suffix)
def humanify_number(number):
suffix = ''
readable = number
if number > 1000000:
suffix = 'M'
readable = number / 1000000.0
elif number > 1000:
suffix = 'K'
readable = number / 1000.0
readable = round(readable, 2)
return '{}{}'.format(readable, suffix)
def build_download_url(uid, use_org_profile=False, active_org=None):
if use_org_profile:
return '{}/{}/models/{}/download'.format(Config.SKETCHFAB_ORGS, active_org["uid"], uid)
else:
return '{}/{}/download'.format(Config.SKETCHFAB_MODEL, uid)
def thumbnail_file_exists(uid):
return os.path.exists(os.path.join(Config.SKETCHFAB_THUMB_DIR, '{}.jpeg'.format(uid)))
def clean_thumbnail_directory():
if not os.path.exists(Config.SKETCHFAB_THUMB_DIR):
return
from os import listdir
for file in listdir(Config.SKETCHFAB_THUMB_DIR):
os.remove(os.path.join(Config.SKETCHFAB_THUMB_DIR, file))
def clean_downloaded_model_dir(uid):
shutil.rmtree(os.path.join(Config.SKETCHFAB_MODEL_DIR, uid))
def get_thumbnail_url(thumbnails_json):
min_height = 1e6
min_thumbnail = None
best_height = 0
best_thumbnail = None
for image in thumbnails_json['images']:
h = image['height']
if h <= Config.MAX_THUMBNAIL_HEIGHT and h > best_height:
best_height = h
best_thumbnail = image['url']
elif h < min_height:
min_height = h
min_thumbnail = image['url']
# Ensure we have a thumbnail if available thumbnails are all above MAX_THUMBNAIL_HEIGHT
if best_thumbnail is None and min_thumbnail is not None:
return min_thumbnail
return best_thumbnail
def setup_plugin():
if not os.path.exists(Config.SKETCHFAB_THUMB_DIR):
os.makedirs(Config.SKETCHFAB_THUMB_DIR)
def get_uid_from_thumbnail_url(thumbnail_url):
return thumbnail_url.split('/')[4]
def get_uid_from_model_url(model_url, use_org_profile=False):
try:
return model_url.split('/')[7] if use_org_profile else model_url.split('/')[5]
except:
ShowMessage("ERROR", "Url parsing error", "Error getting uid from url: {}".format(model_url))
return None
def get_uid_from_download_url(model_url):
return model_url.split('/')[6]
def clean_node_hierarchy(objects, root_name):
"""
Removes the useless nodes in a hierarchy
TODO: Keep the transform (might impact Yup/Zup)
"""
# Find the parent object
root = None
for object in objects:
if object.parent is None:
root = object
if root is None:
return None
# Go down its hierarchy until one child has multiple children, or a single mesh
# Keep the name while deleting objects in the hierarchy
diverges = False
while diverges==False:
children = root.children
if children is not None:
if len(children)>1:
diverges = True
root.name = root_name
if len(children)==1:
if children[0].type != "EMPTY":
diverges = True
root.name = root_name
if children[0].type == "MESH": # should always be the case
matrixcopy = children[0].matrix_world.copy()
children[0].parent = None
children[0].matrix_world = matrixcopy
bpy.data.objects.remove(root)
children[0].name = root_name
root = children[0]
elif children[0].type == "EMPTY":
diverges = False
matrixcopy = children[0].matrix_world.copy()
children[0].parent = None
children[0].matrix_world = matrixcopy
bpy.data.objects.remove(root)
root = children[0]
else:
break
# Select the root Empty node
root.select_set(True)
def is_valid_uuid(uuid_to_test, version=4):
try:
uuid_obj = UUID(hex=uuid_to_test, version=version)
return True
except ValueError:
return False
class Cache:
SKETCHFAB_CACHE_FILE = os.path.join(
bpy.utils.user_resource("SCRIPTS", path="sketchfab_cache", create=True),
".cache"
) # Use a user path to avoid permission-related errors
def read():
if not os.path.exists(Cache.SKETCHFAB_CACHE_FILE):
return {}
with open(Cache.SKETCHFAB_CACHE_FILE, 'rb') as f:
data = f.read().decode('utf-8')
return json.loads(data)
def get_key(key):
cache_data = Cache.read()
if key in cache_data:
return cache_data[key]
def save_key(key, value):
cache_data = Cache.read()
cache_data[key] = value
with open(Cache.SKETCHFAB_CACHE_FILE, 'wb+') as f:
f.write(json.dumps(cache_data).encode('utf-8'))
def delete_key(key):
cache_data = Cache.read()
if key in cache_data:
del cache_data[key]
with open(Cache.SKETCHFAB_CACHE_FILE, 'wb+') as f:
f.write(json.dumps(cache_data).encode('utf-8'))
# helpers
def get_sketchfab_login_props():
return bpy.context.window_manager.sketchfab_api
def get_sketchfab_props():
return bpy.context.window_manager.sketchfab_browser
def get_sketchfab_props_proxy():
return bpy.context.window_manager.sketchfab_browser_proxy
def get_sketchfab_model(uid):
skfb = get_sketchfab_props()
if "current" in skfb.search_results and uid in skfb.search_results["current"]:
return skfb.search_results['current'][uid]
else:
return None
def run_default_search():
searchthr = GetRequestThread(Config.DEFAULT_SEARCH, parse_results)
searchthr.start()
def get_plugin_enabled():
global is_plugin_enabled
return is_plugin_enabled
def refresh_search(self, context):
pprops = get_sketchfab_props_proxy()
if pprops.is_refreshing:
return
props = get_sketchfab_props()
if pprops.search_domain != props.search_domain:
props.search_domain = pprops.search_domain
if pprops.sort_by != props.sort_by:
props.sort_by = pprops.sort_by
if 'current' in props.search_results:
del props.search_results['current']
props.query = pprops.query
props.animated = pprops.animated
props.pbr = pprops.pbr
props.staffpick = pprops.staffpick
props.categories = pprops.categories
props.face_count = pprops.face_count
bpy.ops.wm.sketchfab_search('EXEC_DEFAULT')
def set_login_status(status_type, status):
login_props = get_sketchfab_login_props()
login_props.status = status
login_props.status_type = status_type
def set_import_status(status):
props = get_sketchfab_props()
props.import_status = status
class SketchfabApi:
def __init__(self):
self.access_token = ''
self.api_token = ''
self.headers = {}
self.username = ''
self.display_name = ''
self.plan_type = ''
self.next_results_url = None
self.prev_results_url = None
self.user_orgs = []
self.user_has_orgs = False
self.active_org = None
self.use_org_profile = False
def build_headers(self):
if self.access_token:
self.headers = {'Authorization': 'Bearer ' + self.access_token}
elif self.api_token:
self.headers = {'Authorization': 'Token ' + self.api_token}
else:
print("Empty authorization header")
self.headers = {}
def login(self, email, password, api_token):
bpy.ops.wm.login_modal('INVOKE_DEFAULT')
def is_user_logged(self):
if (self.access_token or self.api_token) and self.headers:
return True
return False
def is_user_pro(self):
return len(self.plan_type) and self.plan_type not in ['basic', 'plus']
def logout(self):
self.access_token = ''
self.api_token = ''
self.headers = {}
Cache.delete_key('username')
Cache.delete_key('access_token')
Cache.delete_key('api_token')
Cache.delete_key('key')
props = get_sketchfab_props()
#props.search_domain = "DEFAULT"
if 'current' in props.search_results:
del props.search_results['current']
pprops = get_sketchfab_props_proxy()
#pprops.search_domain = "DEFAULT"
self.user_orgs = []
self.user_has_orgs = False
self.active_org = None
self.use_org_profile = False
props.use_org_profile = False
pprops.use_org_profile = False
bpy.ops.wm.sketchfab_search('EXEC_DEFAULT')
def request_user_info(self):
requests.get(Config.SKETCHFAB_ME, headers=self.headers, hooks={'response': self.parse_user_info})
def get_user_info(self):
if self.display_name and self.plan_type:
return '{} ({})'.format(self.display_name, self.plan_type)
else:
return ('', '')
def parse_user_info(self, r, *args, **kargs):
if r.status_code == 200:
user_data = r.json()
self.username = user_data['username']
self.display_name = user_data['displayName']
self.plan_type = user_data['account']
requests.get(Config.SKETCHFAB_ME + "/orgs", headers=self.headers, hooks={'response': self.on_user_orgs_check})
else:
print('\nInvalid access or API token\nYou can get your API token here:\nhttps://sketchfab.com/settings/password\n')
set_login_status('ERROR', 'Failed to authenticate')
ShowMessage("ERROR", "Failed to authenticate", "Invalid access or API token")
self.access_token = ''
self.api_token = ''
self.headers = {}
def request_user_orgs(self):
if not self.active_org:
requests.get(Config.SKETCHFAB_ME + "/orgs", headers=self.headers, hooks={'response': self.parse_orgs_info})
pass
def on_user_orgs_check(self, r, *args, **kargs):
self.user_has_orgs = bool((r.status_code == 200) and len(r.json().get("results", [])))
def parse_orgs_info(self, r, *args, **kargs):
"""
Get and store information about user's orgs, and its orgs projects
"""
if r.status_code == 200:
orgs_data = r.json()
# Get a list of the user's orgs
for org in orgs_data["results"]:
self.user_orgs.append({
"uid": org["uid"],
"displayName": org["displayName"],
"username": org["username"],
"url": org["publicProfileUrl"],
"projects": [],
})
self.user_orgs.sort(key = lambda x : x["displayName"])
# Iterate on the orgs to get lists of their projects
for org in self.user_orgs:
# Create the callback inline to keep a reference to the org uid
def parse_projects_info(r, *args, **kargs):
"""
Get and store information about an org projects
"""
if r.status_code == 200:
projects_data = r.json()
projects = projects_data["results"]
# Add the projects to the orgs dict object
for proj in projects:
org_uid = proj["org"]["uid"]
org = next((x for x in self.user_orgs if x["uid"] == org_uid))
org["projects"].append({
"uid": proj["uid"],
"name": proj["name"],
"slug": proj["slug"],
"modelCount": proj["modelCount"],
"memberCount": proj["memberCount"],
})
org["projects"].sort(key = lambda x : x["name"])
# Iterate on all projects (not just the 24 first)
if projects_data["next"] is not None:
requests.get(
projects_data["next"],
headers=self.headers,
hooks={'response': parse_projects_info}
)
else:
print('Can not get projects info')
requests.get("%s/%s/projects" % (Config.SKETCHFAB_ORGS, org["uid"]),
headers=self.headers,
hooks={'response': parse_projects_info})
# Set the first org as active
if len(self.user_orgs):
self.active_org = self.user_orgs[0]
self.user_has_orgs = True
# Iterate on all orgs (not just the 24 first)
if orgs_data["next"] is not None:
requests.get(orgs_data["next"], headers=self.headers, hooks={'response': self.parse_orgs_info})
def request_thumbnail(self, thumbnails_json, model_uid):
# Avoid requesting twice the same data
if model_uid not in thumbnailsProgress:
thumbnailsProgress.add(model_uid)
url = Utils.get_thumbnail_url(thumbnails_json)
thread = ThumbnailCollector(url)
thread.start()
def request_model_info(self, uid, callback=None):
callback = self.handle_model_info if callback is None else callback
url = Config.SKETCHFAB_MODEL + '/' + uid
if self.use_org_profile and self.active_org.get("uid"):
url = Config.SKETCHFAB_ORGS + "/" + self.active_org["uid"] + "/models/" + uid
model_infothr = GetRequestThread(url, callback, self.headers)
model_infothr.start()
def handle_model_info(self, r, *args, **kwargs):
skfb = get_sketchfab_props()
uid = Utils.get_uid_from_model_url(r.url, self.use_org_profile)
# Dirty fix to avoid processing obsolete result data
if 'current' not in skfb.search_results or uid is None or uid not in skfb.search_results['current']:
return
model = skfb.search_results['current'][uid]
json_data = r.json()
model.license = json_data.get('license', {})
if model.license is not None:
model.license = model.license.get('fullName', 'Personal (you own this model)')
anim_count = int(json_data.get('animationCount', 0))
model.animated = 'Yes ({} animation(s))'.format(anim_count) if anim_count > 0 else 'No'
skfb.search_results['current'][uid] = model
def search(self, query, search_cb):
skfb = get_sketchfab_props()
url = Config.BASE_SEARCH
if skfb.search_domain == "OWN":
url = Config.BASE_SEARCH_OWN_MODELS
elif skfb.search_domain == "STORE":
url = Config.PURCHASED_MODELS
elif skfb.search_domain == "ACTIVE_ORG":
url = Config.SKETCHFAB_ORGS + "/%s/models?isArchivesReady=true" % self.active_org["uid"]
elif len(skfb.search_domain) == 32:
url = Config.SKETCHFAB_ORGS + "/%s/models?isArchivesReady=true&projects=%s" % (self.active_org["uid"], skfb.search_domain)
search_query = '{}{}'.format(url, query)
if search_query not in ongoingSearches:
ongoingSearches.add(search_query)
searchthr = GetRequestThread(search_query, search_cb, self.headers)
searchthr.start()
def search_cursor(self, url, search_cb):
requests.get(url, headers=self.headers, hooks={'response': search_cb})
def write_model_info(self, title, author, authorUrl, license, uid):
try:
downloadHistory = bpy.context.preferences.addons[__name__.split('.')[0]].preferences.downloadHistory
if downloadHistory != "":
downloadHistory = os.path.abspath(downloadHistory)
createFile = False
if not os.path.exists(downloadHistory):
createFile = True
with open(downloadHistory, 'a+') as f:
if createFile:
f.write("Model name, Author name, Author url, License, Model link,\n")
f.write("{}, {}, https://sketchfab.com/{}, {}, https://sketchfab.com/models/{},\n".format(
title.replace(",", " "),
author.replace(",", " "),
authorUrl.replace(",", " "),
license.replace(",", " "),
uid
))
except:
print("Error encountered while saving data to history file")
def parse_model_info_request(self, r, *args, **kargs):
try:
if r.status_code == 200:
result = r.json()
title = result['name']
author = result['user']['displayName']
username = result['user']['username']
license = result["license"]["label"]
uid = result['uid']
self.write_model_info(title, author, username, license, uid)
else:
print("Error encountered while getting model info ({})\n{}\n{}".format(r.status_code, r.url, str(r.json())))
except:
print("Error encountered while parsing model info request: {}".format(r.url))
def download_model(self, uid):
skfb_model = get_sketchfab_model(uid)
if skfb_model is not None: # The model comes from the search results
if skfb_model.download_url and (time.time() - skfb_model.time_url_requested < skfb_model.url_expires):
self.get_archive(skfb_model.download_url)
else:
skfb_model.download_url = None
skfb_model.url_expires = None
skfb_model.time_url_requested = None
self.write_model_info(skfb_model.title, skfb_model.author, skfb_model.username, skfb_model.license, uid)
requests.get(Utils.build_download_url(uid, self.use_org_profile, self.active_org), headers=self.headers, hooks={'response': self.handle_download})
else: # Model comes from a direct link
skfb = get_sketchfab_props()
download_url = ""
# If the model is in an org, find if the user has access to it
if "/orgs/" in skfb.manualImportPath:
try:
orgName = skfb.manualImportPath.split("/orgs/")[1].split("/")[0]
if skfb.skfb_api.user_has_orgs and not skfb.skfb_api.active_org:
skfb.skfb_api.request_user_orgs()
user_orgs = skfb.skfb_api.user_orgs
orgUid = ""
for org in user_orgs:
if org["username"] == orgName:
orgUid = org["uid"]
break
if orgUid:
download_url = '{}/{}/models/{}/download'.format(Config.SKETCHFAB_ORGS, orgUid, uid)
else:
ShowMessage("ERROR", "User not in Organization", "User does not appear to belong to org %s" % (orgName))
return
except:
ShowMessage("ERROR", "Invalid url", "Cannot parse org name from url %s" % skfb.manualImportPath)
return
# Otherwise, request a direct download and get model info
else:
download_url = Utils.build_download_url(uid)
requests.get('{}/{}'.format(Config.SKETCHFAB_MODEL, uid), headers=skfb.skfb_api.headers, hooks={'response': self.parse_model_info_request})
requests.get(download_url, headers=self.headers, hooks={'response': self.handle_download})
def handle_download(self, r, *args, **kwargs):
if r.status_code != 200 or 'gltf' not in r.json():
ShowMessage("ERROR", "This model is not downloadable", "Make sure your account has enough rights to download the model")
return
skfb = get_sketchfab_props()
uid = Utils.get_uid_from_model_url(r.url, self.use_org_profile)
if uid is None:
return
gltf = r.json()['gltf']
skfb_model = get_sketchfab_model(uid)
# If the model name is not known at this step, we could try to do an additional API call to get it
# This can happen when the user chose to import a model from its url
# However this adds an additional call and a bit of complexity for org models (need additional parsing),
# so for a simple hotfix models imported this way will be called "Sketchfab model"
self.get_archive(gltf['url'], skfb_model.title if skfb_model else "Sketchfab Model")
def get_archive(self, url, title):
if url is None:
print('Url is None')
return
r = requests.get(url, stream=True)
uid = Utils.get_uid_from_download_url(url)
temp_dir = os.path.join(Config.SKETCHFAB_MODEL_DIR, uid)
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
archive_path = os.path.join(temp_dir, '{}.zip'.format(uid))
if not os.path.exists(archive_path):
wm = bpy.context.window_manager
wm.progress_begin(0, 100)
set_log("Downloading model..")
with open(archive_path, "wb") as f:
total_length = r.headers.get('content-length')
if total_length is None: # no content length header
f.write(r.content)
else:
dl = 0
total_length = int(total_length)
for data in r.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
done = int(100 * dl / total_length)
wm.progress_update(done)
set_log("Downloading model..{}%".format(done))
wm.progress_end()
else:
print('Model already downloaded')
gltf_path, gltf_zip = unzip_archive(archive_path)
if gltf_path:
try:
import_model(gltf_path, uid, title)
except Exception as e:
import traceback
print(traceback.format_exc())
else:
ShowMessage("ERROR", "Download error", "Failed to download model (url might be invalid)")
model = get_sketchfab_model(uid)
set_import_status("Import model ({})".format(model.download_size if model.download_size else 'fetching data'))
return
class SketchfabLoginProps(bpy.types.PropertyGroup):
def update_tr(self, context):
self.status = ''
if self.email != self.last_username or self.password != self.last_password:
self.last_username = self.email
self.last_password = self.password
if not self.password:
set_login_status('ERROR', 'Password is empty')
bpy.ops.wm.sketchfab_login('EXEC_DEFAULT')
email : StringProperty(
name="email",
description="User email",
default=""
)
api_token : StringProperty(
name="API Token",
description="User API Token",
default=""
)
use_mail : BoolProperty(
name="Use mail / password",
description="Use mail/password login or API Token",
default=True,
)
password : StringProperty(
name="password",
description="User password",
subtype='PASSWORD',
default="",
update=update_tr
)
access_token : StringProperty(
name="access_token",
description="oauth access token",
subtype='PASSWORD',
default=""
)
status : StringProperty(name='', default='')
status_type : EnumProperty(
name="Login status type",
items=(('ERROR', "Error", ""),
('INFO', "Information", ""),
('FILE_REFRESH', "Progress", "")),
description="Determines which icon to use",
default='FILE_REFRESH'
)
last_username : StringProperty(default="default")
last_password : StringProperty(default="default")
skfb_api = SketchfabApi()
def get_user_orgs(self, context):
api = get_sketchfab_props().skfb_api
if not api.user_has_orgs:
api.request_user_orgs()
return [(org["uid"], org["displayName"], "") for org in api.user_orgs]
def get_org_projects(self, context):
api = get_sketchfab_props().skfb_api
return [(proj["uid"], proj["name"], proj["name"]) for proj in api.active_org["projects"]]
def get_available_search_domains(self, context):
api = get_sketchfab_props().skfb_api
search_domains = [domain for domain in Config.SKETCHFAB_SEARCH_DOMAIN]
if api.user_has_orgs and api.use_org_profile:
search_domains = [
("ACTIVE_ORG", "Active Organization", api.active_org["displayName"], 0)
]
for p in get_org_projects(self, context):
search_domains.append(p)
return tuple(search_domains)
def refresh_orgs(self, context):
pprops = get_sketchfab_props_proxy()
if pprops.is_refreshing:
return
props = get_sketchfab_props()
api = props.skfb_api
api.use_org_profile = pprops.use_org_profile
if api.user_has_orgs and not api.active_org :
bpy.context.window.cursor_set("WAIT")
api.request_user_orgs()
bpy.context.window.cursor_set("DEFAULT")
orgs = [org for org in api.user_orgs if org["uid"] == pprops.active_org]
api.active_org = orgs[0] if len(orgs) else None
if pprops.use_org_profile != props.use_org_profile:
props.use_org_profile = pprops.use_org_profile
if pprops.active_org != props.active_org:
props.active_org = pprops.active_org
if props.use_org_profile:
props.search_domain = "ACTIVE_ORG"
pprops.search_domain = "ACTIVE_ORG"
else:
props.search_domain = "DEFAULT"
pprops.search_domain = "DEFAULT"
refresh_search(self, context)
def get_sorting_options(self, context):
api = get_sketchfab_props().skfb_api
if api.user_has_orgs and api.use_org_profile:
return (
('RELEVANCE', "Relevance", ""),
('RECENT', "Recent", "")
)
else:
return Config.SKETCHFAB_SORT_BY
class SketchfabBrowserPropsProxy(bpy.types.PropertyGroup):
# Search
query : StringProperty(
name="",
update=refresh_search,
description="Query to search",
default="",
options={'SKIP_SAVE'}
)
pbr : BoolProperty(
name="PBR",
description="Search for PBR model only",
default=False,
update=refresh_search,
)
categories : EnumProperty(
name="Categories",
items=Config.SKETCHFAB_CATEGORIES,
description="Show only models of category",
default='ALL',
update=refresh_search
)
face_count : EnumProperty(
name="Face Count",
items=Config.SKETCHFAB_FACECOUNT,
description="Determines which meshes are exported",
default='ANY',
update=refresh_search
)
sort_by : EnumProperty(
name="Sort by",
items=get_sorting_options,
description="Sort ",
update=refresh_search,
)
animated : BoolProperty(
name="Animated",
description="Show only models with animation",
default=False,
update=refresh_search
)
staffpick : BoolProperty(
name="Staffpick",
description="Show only staffpick models",
default=False,
update=refresh_search
)
search_domain : EnumProperty(
name="",
items=get_available_search_domains,
description="Search domain ",
update=refresh_search,
default=None
)
use_org_profile : BoolProperty(
name="Use organisation profile",
description="Download/Upload as a member of an organization.\nSearch queries and uploads will be performed to\nthe organisation and project selected below",
default=False,
update=refresh_orgs
)
active_org : EnumProperty(
name="Org",
items=get_user_orgs,
description="Active org",
update=refresh_orgs
)
is_refreshing : BoolProperty(
name="Refresh",
description="Refresh",
default=False,
)
expanded_filters : bpy.props.BoolProperty(default=False)
class SketchfabBrowserProps(bpy.types.PropertyGroup):
# Search
query : StringProperty(
name="Search",
description="Query to search",
default=""
)
pbr : BoolProperty(
name="PBR",
description="Search for PBR model only",
default=False
)
categories : EnumProperty(
name="Categories",
items=Config.SKETCHFAB_CATEGORIES,
description="Show only models of category",
default='ALL',
)
face_count : EnumProperty(
name="Face Count",
items=Config.SKETCHFAB_FACECOUNT,
description="Determines which meshes are exported",
default='ANY',
)
sort_by : EnumProperty(
name="Sort by",
items=get_sorting_options,
description="Sort ",
)
animated : BoolProperty(
name="Animated",
description="Show only models with animation",
default=False,
)
staffpick : BoolProperty(
name="Staffpick",
description="Show only staffpick models",
default=False,
)
search_domain : EnumProperty(
name="Search domain",
items=get_available_search_domains,
description="Search domain ",
)
use_org_profile : BoolProperty(