-
Notifications
You must be signed in to change notification settings - Fork 1
/
pluginManager.py
658 lines (530 loc) · 22.3 KB
/
pluginManager.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
* File Name : pluginManager.py
* Purpose : Plugin Manager that fetches plugins from GitHub and FC Wiki
* Creation Date : 06-06-2016
* Copyright (c) 2016 Mandeep Singh <[email protected]>
"""
from __future__ import print_function
import re
import os
from socket import gaierror
# Guide to import FreeCAD:
# https://mandeep7.wordpress.com/2016/07/23/import-freecad-in-python/
import FreeCAD
import shutil
import glob
# import ipdb
class Plugin():
"Information about plugin."
# def __init__(self, name, author, plugin_type, description, baseurl,
# infourl):
# def __init__(self, name, author, baseurl, description):
def __init__(self, name, baseurl, plugin_type, author=None,
description=None, version=None, directory=None):
"returns plugin info"
self.name = name
self.author = author
self.baseurl = baseurl
self.description = description
self.plugin_type = plugin_type
self.fetch = self
self.plugin_dir = directory
self.version = version
# self.infourl = infourl
def __repr__(self):
return 'Plugin(%s)' % (self.name)
class Fetch(object):
"The base fetch class"
def __init__(self):
print("Object created")
return
def getPluginsList(self):
print("Plugins list")
return
def getInfo(self, plugin):
return plugin
def isInstalled(self, plugin):
print("If installed or not")
return
def install(self, plugin):
print("Installing")
return
def isUpToDate(self, plugin):
print("Check for latest version")
return
def uninstall(self, plugin):
print("Un-installation")
return
def update(self, plugin):
print("Update the plugin")
return
class FetchFromGitHub(Fetch):
"class to get workbenches from GitHub"
def __init__(self):
print("Fetching GitHub Workbenches")
# For storing instances of Plugin() class.
self.instances = {}
self.gitPlugins = []
self.plugin_type = "Workbench"
# Specify the directory where the Workbenches are to be installed.
self.workbench_path = os.path.join(FreeCAD.ConfigGet("UserAppData"),
"Mod")
# If any of the paths do not exist, then create one.
if not os.path.exists(self.workbench_path):
os.makedirs(self.workbench_path)
def githubAuth(self):
"A common function for github authentication"
from github import Github
"""Github API token. Create one at
https://github.com/settings/tokens/new and replace it by "None" below.
"""
token = None
git = Github(token)
return git
def getPluginsList(self):
"Get a list of GitHub Plugins"
try:
git = self.githubAuth()
github_username = "FreeCAD"
# Name of the repository residing at github_username account.
repository = "FreeCAD-addons"
# Repository instance.
repo = git.get_user(github_username).get_repo(repository)
print("Fetching repository details...")
# Fetching repository contents.
repo_content = repo.get_dir_contents("")
# Iterations to fetch submodule entries and their info.
for item in repo_content:
url = str(item.html_url)
try:
gitUrl = re.search('(.+?)/tree', url).group(1)
except:
pass
else:
# print(item.name)
# print(gitUrl)
instance = Plugin(item.name, gitUrl, self.plugin_type)
instance.fetch = self
self.instances[str(item.name)] = instance
# ipdb.set_trace()
# print("\nPlugins: ", self.instances)
return self.instances.values()
# except gaierror or timeout:
except gaierror:
print("Please check your network connection!")
except KeyboardInterrupt:
print("\nInterrupted by Keyboard!")
except ImportError:
print("PyGithub isn't installed!")
"""except GithubException:
print("API limit exceeded!")
except:
print("Please check your network connection!")
"""
def getInfo(self, targetPlugin):
"Get additional information about a specific plugin (GitHub)."
git = self.githubAuth()
# Checks if the additional information has already been fetched.
if targetPlugin.author is not None and targetPlugin.description \
is not None:
print("Already in the list...")
return targetPlugin
# If information isn't there, then fetch it and store it to the dict.
else:
# ipdb.set_trace()
# Check if a plugin is present in the plugin list.
for instance in self.instances.values():
if(targetPlugin.name == instance.name):
# Getting the submodule info like author, description.
submodule_repoInfo = re.search('https://github.com/(.+?)$',
instance.baseurl).group(1)
submodule_repo = git.get_repo(submodule_repoInfo)
# submodule_author = submodule_repo.owner.name
submodule_author = submodule_repo.owner.login
submodule_description = submodule_repo.description
# print(submodule_author, submodule_description)
# ipdb.set_trace()
# import IPython; IPython.embed()
# Modifying the Plugin class instance.
print(instance.name, "\n", instance.baseurl, "\n",
self.plugin_type, "\n", submodule_author, "\n",
submodule_description)
targetPlugin.description = submodule_description
targetPlugin.author = submodule_author
# targetPlugin.version = submodule_version
self.gitPlugins.append(targetPlugin)
break
# ipdb.set_trace()
return targetPlugin
def isInstalled(self, plugin):
"""Checks and returns True if the plugin is already installed,
else returns false.
"""
self.install_dir = os.path.join(self.workbench_path, plugin.name)
print(self.install_dir)
# Associate the plugin directory with the plugin instance.
plugin.plugin_dir = self.install_dir
# Checks if the plugin installation path already exists.
if os.path.exists(self.install_dir):
return True
else:
return False
def install(self, plugin):
"Installs a GitHub plugin"
print("Installing...", plugin.name)
try:
import git
except ImportError:
print("Install git module")
# Clone the GitHub repository via the URL.
# git.Git().clone(str(plugin.baseurl), install_dir)
# Checks if the plugin installation path already exists.
if not self.isInstalled(plugin):
"""Clone the GitHub repository via Plugin URL to install_dir and
with depth=1 (shallow clone).
"""
git.Repo.clone_from(plugin.baseurl, self.install_dir, depth=1)
print("Done!")
return True
else:
print("Plugin already installed!")
return False
def isUpToDate(self, targetPlugin):
"Checks if the plugin is up to date or not"
# First checks if the plugin is installed!
if self.isInstalled(targetPlugin) is True:
# Gets the version of installed plugin.
from git import Repo
print(targetPlugin.plugin_dir)
self.repository = Repo(targetPlugin.plugin_dir)
print("It is installed!")
# Fetch information from the remote repository.
self.repository.git.fetch()
# Gets the `git status` of the repository.
git_status = self.repository.git.status()
# Checks if the repository is up-to-date with remote.
if re.findall("clean", git_status) or \
re.findall("up-to-date", git_status):
print("Latest version already installed!")
return True
elif re.findall("behind", git_status) or \
re.findall("git pull", git_status):
# New version available!
print("New version available!")
return False
else:
# If the plugin isn't installed.
print("Plugin isn't already installed!")
return None
def uninstall(self, plugin):
"Uninstall a GitHub workbench"
if self.isInstalled(plugin):
# Possible ToDo: Add exception for permission check.
print("Un-installing....", self.install_dir)
shutil.rmtree(self.install_dir)
print("Successfully uninstalled!")
return True
else:
print("Invalid plugin!")
return False
def update(self, plugin):
"Update a GitHub workbench"
if self.isUpToDate(plugin) is False:
print("Updating...")
# git pull the changes to update the plugin.
self.repository.git.pull()
print("Plugin successfully updated!")
return True
else:
print("Plugin already up-to-date.")
return False
class FetchFromWiki(Fetch):
"Fetching macros listed on the FreeCAD Wiki"
def __init__(self):
print("Fetching Macros from FC Wiki")
self.macro_instances = []
self.plugin_type = "Macro"
# ipdb.set_trace()
# Get the user-preferred Macro directory.
fc_macro = "User parameter:BaseApp/Preferences/Macro"
self.macro_path = FreeCAD.ParamGet(fc_macro).GetString("MacroPath")
# If not specified by user, then set a default one.
if not self.macro_path:
self.macro_path = os.path.join(FreeCAD.ConfigGet("UserAppData"),
"Macro")
# If any of the paths do not exist, then create one.
if not os.path.exists(self.macro_path):
os.makedirs(self.macro_path)
def getPluginsList(self):
"Get a list of plugins available on the FreeCAD Wiki"
try:
import requests
import bs4
# FreeCAD Macro page.
source_link = "http://www.freecadweb.org/wiki/index.php?title=Macros_recipes"
"""source_link = "http://www.freecadweb.org/wiki/
index.php?title=Sandbox:Macro_Recipes"
"""
# Generating parsed HTML tree from the URL.
req = requests.get(source_link, timeout=15)
soup = bs4.BeautifulSoup(req.text, 'html.parser')
# soup = bs4.BeautifulSoup(open("index.html"), 'html.parser')
# Selects the spans with class MacroLink enclosing the macro links.
macros = soup.select("span.MacroLink")
# for macro in macros[:5]:
for macro in macros:
# Prints macro name
# ipdb.set_trace()
# Due to the additional <a> tag of new macro icon on wiki.
macro = macro.findAllNext()[2]
macro_name = macro.getText()
# Macro URL.
macro_url = "http://freecadweb.org" + macro.get("href")
# print(macro_name, macro_url)
macro_instance = Plugin(macro_name, macro_url,
self.plugin_type)
macro_instance.fetch = self
self.macro_instances.append(macro_instance)
except requests.exceptions.ConnectionError:
print("Please check your network connection!")
except KeyboardInterrupt:
print("\nInterrupted by Keyboard!")
except ImportError:
print("\nMake sure requests and BeautifulSoup are installed!")
# print("\nPlugins:", self.macro_instances)
# ipdb.set_trace()
return self.macro_instances
def macroWeb(self, targetPlugin):
"""Returns the parsed Macro Web page object. Separated, to be used
by another functions.
"""
try:
import requests
import bs4
if targetPlugin in self.macro_instances:
macro_page = requests.get(targetPlugin.baseurl)
soup = bs4.BeautifulSoup(macro_page.text, 'html.parser')
return soup
else:
print("Unknown Plugin!", targetPlugin)
except requests.exceptions.ConnectionError:
print("Please check your network connection!")
def getInfo(self, targetPlugin):
"Getting additional information about a plugin (macro)"
# Checks if the additional information has already been fetched.""
if targetPlugin.author is not None and targetPlugin.version \
is not None:
print("Already in the list...")
return targetPlugin
# If information isn't there, then fetch it and store it to the dict.
else:
try:
# ipdb.set_trace()
# import IPython; IPython.embed()
# Use the same URL to fetch macro desciption and macro author
macro = self.macroWeb(targetPlugin)
macro_description = macro.select(".macro-description")[0].getText()
macro_author = macro.select(".macro-author")[0].getText()
macro_version = macro.select(".macro-version")[0].getText().replace("\n", "")
except IndexError:
print("Macro Information not found! Skipping Macro...")
else:
"""macro_instance = Plugin(macro_name, macro_author, macro_url,
macro_description)
"""
# Modifying the plugin information.
targetPlugin.description = macro_description
targetPlugin.author = macro_author
targetPlugin.version = macro_version
print(targetPlugin.name, "\n", targetPlugin.baseurl, "\n",
self.plugin_type, "\n", macro_author, "\n",
macro_description, macro_version)
return targetPlugin
def isInstalled(self, targetPlugin):
"""Checks and returns True if the plugin is already installed,
else returns false.
"""
# Get plugin information.
info = self.getInfo(targetPlugin)
# Store version information after removing new line from it.
version = info.version
# The macro installation path.
self.plugin_path = os.path.join(self.macro_path, targetPlugin.name)
# Append macro version and extension to the macro path.
self.install_dir = self.plugin_path + "_" + version + ".FCMacro"
# Associate the install_dir to the Plugin instance itself.
targetPlugin.plugin_dir = self.install_dir
print(targetPlugin.plugin_dir)
# Checks if the plugin installation path already exists with any
# version.
self.exists = glob.glob(self.plugin_path + "*" + ".FCMacro")
try:
# If the path exists, then return True and collect its version.
if self.exists[0]:
print("Macro already installed.")
try:
# Fetches the currently installed macro version.
self.installed_version = re.search('_(\d.+?).FCMacro',
self.exists[0]).group(1)
except AttributeError:
print("Macro with Invalid version found!")
"""# Remove if multiple versions installed.
for path in self.exists:
os.remove(path)
"""
return False
else:
return True
else:
print("Macro isn't installed.")
return False
except IndexError:
print("Plugin not installed.")
return False
def install(self, targetPlugin):
"Installs the Macro"
print("Installing...", targetPlugin.name)
# Lambda function to check the path existence.
# self.isThere = lambda path: os.path.exists(path)
# ipdb.set_trace()
macro = self.macroWeb(targetPlugin)
try:
try:
# macro_code = macro.select(".mw-highlight.mw-content-ltr.macro-code")[0].getText()
# ipdb.set_trace()
macro_code = macro.select("pre")[0].getText()
except IndexError:
macro_code = macro.select(".mw-highlight.mw-content-ltr")[0].getText()
else:
print("Nothing there!")
"""except:
print("No code found!")
"""
# else:
# try:
# Checks if the plugin installation path already exists.
except:
print("Macro fetching Error!")
else:
if not self.isInstalled(targetPlugin):
from html.parser import HTMLParser
macro_file = open(self.install_dir, 'w+')
# ipdb.set_trace()
macro_code = HTMLParser().unescape(macro_code)
# macro_code = macro_code.replace("\xc2\xa0", " ")
macro_file.write(macro_code.encode("utf8"))
macro_file.close()
print("Done!")
return True
else:
print("Plugin already installed!")
return False
"""
except:
print("Couldn't create the file", install_dir)
"""
def isUpToDate(self, targetPlugin):
"Checks if the plugin is up to date or not"
# First checks if the plugin is installed!
if self.isInstalled(targetPlugin) is True:
"""
# Gets the version of installed plugin.
try:
current_version = re.search('_(\d.+?).FCMacro', targetPlugin.plugin_dir).group(1)
# current_version = re.findall('_(\d.+?).FCMacro', targetPlugin.plugin_dir)
except TypeError:
print("Unexpectedly, couldn't get the plugin dir!")
"""
# Compares local version with the remote version.
if self.installed_version is targetPlugin.version:
print("Latest version already installed!")
return True
else:
# New version available!
return False
else:
# If the plugin isn't installed.
print("Plugin isn't already installed!")
return None
def uninstall(self, targetPlugin):
"Uninstalls a Macro plugin"
if self.isInstalled(targetPlugin):
print("Un-installing....", self.exists[0])
os.remove(self.exists[0])
return True
else:
print("Invalid plugin")
return False
def update(self, targetPlugin):
"Update a Macro plugin"
if self.isUpToDate(targetPlugin) is False:
print("Updating...")
backup_file = self.exists[0] + ".bak"
os.rename(self.exists[0], backup_file)
# Downloading the Macro again to update the plugin and remove
# backup file.
if self.install(targetPlugin) is True:
os.remove(backup_file)
print("Plugin successfully updated!")
return True
else:
print("Plugin already up-to-date.")
return False
class PluginManager():
"An interface to manage all plugins"
def __init__(self):
# ipdb.set_trace()
gObj = FetchFromGitHub()
mac = FetchFromWiki()
try:
self.totalPlugins = gObj.getPluginsList() + mac.getPluginsList()
"""The blacklisted plugins are those that can not be installed.
And that do not contain code.
"""
self.blacklisted_plugins_list = ["Macro BOLTS",
"Macro PartsLibrary",
"Macro FCGear",
"Macro WorkFeatures"]
except:
print("Please check the connection!")
exit()
def allPlugins(self):
"Returns all of the available plugins"
# ipdb.set_trace()
# Removes the blacklisted Plugins.
for index, plugin in enumerate(self.totalPlugins):
if plugin.name in self.blacklisted_plugins_list:
del self.totalPlugins[index]
# ipdb.set_trace()
return self.totalPlugins
def info(self, targetPlugin):
"Get additional information about a plugin"
# ipdb.set_trace()
# import IPython; IPython.embed()
if targetPlugin in self.totalPlugins:
print("\nGetting information about", targetPlugin, "...")
# ipdb.set_trace()
pluginInfo = targetPlugin.fetch.getInfo(targetPlugin)
return pluginInfo
def isInstalled(self, targetPlugin):
"Checks if the plugin is installed or not"
if targetPlugin in self.totalPlugins:
return targetPlugin.fetch.isInstalled(targetPlugin)
def install(self, targetPlugin):
"Install a plugin"
if targetPlugin in self.totalPlugins:
return targetPlugin.fetch.install(targetPlugin)
def isUpToDate(self, targetPlugin):
"Checks if the plugin is up to date"
if targetPlugin in self.totalPlugins:
return targetPlugin.fetch.isUpToDate(targetPlugin)
def uninstall(self, targetPlugin):
"Uninstall a plugin"
if targetPlugin in self.totalPlugins:
return targetPlugin.fetch.uninstall(targetPlugin)
def update(self, targetPlugin):
"Update a plugin"
if targetPlugin in self.totalPlugins:
return targetPlugin.fetch.update(targetPlugin)