Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

705 righe
22 KiB

  1. #!/usr/bin/env python2.7
  2. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  3. # MIT License. See license.txt
  4. from __future__ import unicode_literals
  5. import sys
  6. if __name__=="__main__":
  7. sys.path = [".", "lib", "app"] + sys.path
  8. import webnotes
  9. def main():
  10. parsed_args = webnotes._dict(vars(setup_parser()))
  11. fn = get_function(parsed_args)
  12. if parsed_args.get("site")=="all":
  13. for site in get_sites():
  14. args = parsed_args.copy()
  15. args["site"] = site
  16. run(fn, args)
  17. else:
  18. run(fn, parsed_args)
  19. def cmd(fn):
  20. def new_fn(*args, **kwargs):
  21. import inspect
  22. fnargs, varargs, varkw, defaults = inspect.getargspec(fn)
  23. new_kwargs = {}
  24. for a in fnargs:
  25. if a in kwargs:
  26. new_kwargs[a] = kwargs.get(a)
  27. return fn(*args, **new_kwargs)
  28. return new_fn
  29. def run(fn, args):
  30. if isinstance(args.get(fn), (list, tuple)):
  31. out = globals().get(fn)(*args.get(fn), **args)
  32. else:
  33. out = globals().get(fn)(**args)
  34. return out
  35. def get_function(args):
  36. for fn, val in args.items():
  37. if (val or isinstance(val, list)) and globals().get(fn):
  38. return fn
  39. def get_sites():
  40. import os
  41. import conf
  42. return [site for site in os.listdir(conf.sites_dir)
  43. if not os.path.islink(os.path.join(conf.sites_dir, site))
  44. and os.path.isdir(os.path.join(conf.sites_dir, site))]
  45. def setup_parser():
  46. import argparse
  47. parser = argparse.ArgumentParser(description="Run webnotes utility functions")
  48. setup_install(parser)
  49. setup_utilities(parser)
  50. setup_translation(parser)
  51. setup_git(parser)
  52. # common
  53. parser.add_argument("-f", "--force", default=False, action="store_true",
  54. help="Force execution where applicable (look for [-f] in help)")
  55. parser.add_argument("--quiet", default=True, action="store_false", dest="verbose",
  56. help="Show verbose output where applicable")
  57. parser.add_argument("--site", nargs="?", metavar="SITE-NAME or all",
  58. help="Run for a particular site")
  59. return parser.parse_args()
  60. def setup_install(parser):
  61. parser.add_argument("--install", metavar="DB-NAME", nargs=1,
  62. help="Install a new app")
  63. parser.add_argument("--root-password", nargs=1,
  64. help="Root password for new app")
  65. parser.add_argument("--reinstall", default=False, action="store_true",
  66. help="Install a fresh app in db_name specified in conf.py")
  67. parser.add_argument("--restore", metavar=("DB-NAME", "SQL-FILE"), nargs=2,
  68. help="Restore from an sql file")
  69. parser.add_argument("--install_fixtures", default=False, action="store_true",
  70. help="(Re)Install install-fixtures from app/startup/install_fixtures")
  71. parser.add_argument("--make_demo", default=False, action="store_true",
  72. help="Install demo in demo_db_name specified in conf.py")
  73. parser.add_argument("--make_demo_fresh", default=False, action="store_true",
  74. help="(Re)Install demo in demo_db_name specified in conf.py")
  75. parser.add_argument("--add_system_manager", nargs="+",
  76. metavar=("EMAIL", "[FIRST-NAME] [LAST-NAME]"), help="Add a user with all roles")
  77. def setup_utilities(parser):
  78. # update
  79. parser.add_argument("-u", "--update", nargs="*", metavar=("REMOTE", "BRANCH"),
  80. help="Perform git pull, run patches, sync schema and rebuild files/translations")
  81. parser.add_argument("--reload_gunicorn", default=False, action="store_true", help="reload gunicorn on update")
  82. parser.add_argument("--patch", nargs=1, metavar="PATCH-MODULE",
  83. help="Run a particular patch [-f]")
  84. parser.add_argument("-l", "--latest", default=False, action="store_true",
  85. help="Run patches, sync schema and rebuild files/translations")
  86. parser.add_argument("--sync_all", default=False, action="store_true",
  87. help="Reload all doctypes, pages, etc. using txt files [-f]")
  88. parser.add_argument("--update_all_sites", nargs="*", metavar=("REMOTE", "BRANCH"),
  89. help="Perform git pull, run patches, sync schema and rebuild files/translations")
  90. parser.add_argument("--reload_doc", nargs=3,
  91. metavar=('"MODULE"', '"DOCTYPE"', '"DOCNAME"'))
  92. # build
  93. parser.add_argument("-b", "--build", default=False, action="store_true",
  94. help="Minify + concatenate JS and CSS files, build translations")
  95. parser.add_argument("-w", "--watch", default=False, action="store_true",
  96. help="Watch and concatenate JS and CSS files as and when they change")
  97. # misc
  98. parser.add_argument("--backup", default=False, action="store_true",
  99. help="Take backup of database in backup folder [--with_files]")
  100. parser.add_argument("--move", default=False, action="store_true",
  101. help="Move site to different directory defined by --dest_dir")
  102. parser.add_argument("--dest_dir", nargs=1, metavar="DEST-DIR",
  103. help="Move site to different directory")
  104. parser.add_argument("--with_files", default=False, action="store_true",
  105. help="Also take backup of files")
  106. parser.add_argument("--docs", default=False, action="store_true",
  107. help="Build docs")
  108. parser.add_argument("--domain", nargs="*",
  109. help="Get or set domain in Website Settings")
  110. parser.add_argument("--make_conf", nargs="*", metavar=("DB-NAME", "DB-PASSWORD"),
  111. help="Create new conf.py file")
  112. parser.add_argument("--make_custom_server_script", nargs=1, metavar="DOCTYPE",
  113. help="Create new conf.py file")
  114. parser.add_argument("--set_admin_password", metavar='ADMIN-PASSWORD', nargs=1,
  115. help="Set administrator password")
  116. parser.add_argument("--mysql", action="store_true", help="get mysql shell for a site")
  117. parser.add_argument("--serve", action="store_true", help="Run development server")
  118. parser.add_argument("--smtp", action="store_true", help="Run smtp debug server",
  119. dest="smtp_debug_server")
  120. parser.add_argument("--python", action="store_true", help="get python shell for a site")
  121. parser.add_argument("--get_site_status", action="store_true", help="Get site details")
  122. parser.add_argument("--update_site_config", nargs=1,
  123. metavar="SITE-CONFIG-JSON",
  124. help="Update site_config.json for a given --site")
  125. parser.add_argument("--port", default=8000, type=int, help="port for development server")
  126. # clear
  127. parser.add_argument("--clear_web", default=False, action="store_true",
  128. help="Clear website cache")
  129. parser.add_argument("--clear_cache", default=False, action="store_true",
  130. help="Clear cache, doctype cache and defaults")
  131. parser.add_argument("--reset_perms", default=False, action="store_true",
  132. help="Reset permissions for all doctypes")
  133. # scheduler
  134. parser.add_argument("--run_scheduler", default=False, action="store_true",
  135. help="Trigger scheduler")
  136. parser.add_argument("--run_scheduler_event", nargs=1,
  137. metavar="all | daily | weekly | monthly",
  138. help="Run a scheduler event")
  139. # replace
  140. parser.add_argument("--replace", nargs=3,
  141. metavar=("SEARCH-REGEX", "REPLACE-BY", "FILE-EXTN"),
  142. help="Multi-file search-replace [-f]")
  143. # import/export
  144. parser.add_argument("--export_doc", nargs=2, metavar=('"DOCTYPE"', '"DOCNAME"'))
  145. parser.add_argument("--export_doclist", nargs=3, metavar=("DOCTYPE", "NAME", "PATH"),
  146. help="""Export doclist as json to the given path, use '-' as name for Singles.""")
  147. parser.add_argument("--export_csv", nargs=2, metavar=("DOCTYPE", "PATH"),
  148. help="""Dump DocType as csv""")
  149. parser.add_argument("--import_doclist", nargs=1, metavar="PATH",
  150. help="""Import (insert/update) doclist. If the argument is a directory, all files ending with .json are imported""")
  151. def setup_git(parser):
  152. parser.add_argument("--pull", nargs="*", metavar=("REMOTE", "BRANCH"),
  153. help="Run git pull for both repositories")
  154. parser.add_argument("-p", "--push", nargs="*", metavar=("REMOTE", "BRANCH"),
  155. help="Run git push for both repositories")
  156. parser.add_argument("--status", default=False, action="store_true",
  157. help="Run git status for both repositories")
  158. parser.add_argument("--commit", nargs=1, metavar="COMMIT-MSG",
  159. help="Run git commit COMMIT-MSG for both repositories")
  160. parser.add_argument("--checkout", nargs=1, metavar="BRANCH",
  161. help="Run git checkout BRANCH for both repositories")
  162. parser.add_argument("--git", nargs="*", metavar="OPTIONS",
  163. help="Run git command for both repositories")
  164. def setup_translation(parser):
  165. parser.add_argument("--build_message_files", default=False, action="store_true",
  166. help="Build message files for translation")
  167. parser.add_argument("--export_messages", nargs=2, metavar=("LANG-CODE", "FILENAME"),
  168. help="""Export all messages for a language to translation in a csv file.
  169. Example, lib/wnf.py --export_messages hi hindi.csv""")
  170. parser.add_argument("--import_messages", nargs=2, metavar=("LANG-CODE", "FILENAME"),
  171. help="""Import messages for a language and make language files.
  172. Example, lib/wnf.py --import_messages hi hindi.csv""")
  173. parser.add_argument("--google_translate", nargs=3,
  174. metavar=("LANG-CODE", "INFILE", "OUTFILE"),
  175. help="Auto translate using Google Translate API")
  176. parser.add_argument("--translate", nargs=1, metavar="LANG-CODE",
  177. help="""Rebuild translation for the given langauge and
  178. use Google Translate to tranlate untranslated messages. use "all" """)
  179. # methods
  180. # install
  181. @cmd
  182. def install(db_name, source_sql=None, site=None, verbose=True, force=False, root_password=None, site_config=None, admin_password='admin'):
  183. from webnotes.install_lib.install import Installer
  184. inst = Installer('root', db_name=db_name, site=site, root_password=root_password, site_config=site_config)
  185. inst.install(db_name, source_sql=source_sql, verbose=verbose, force=force, admin_password=admin_password)
  186. webnotes.destroy()
  187. @cmd
  188. def reinstall(site=None, verbose=True):
  189. webnotes.init(site=site)
  190. install(webnotes.conf.db_name, site=site, verbose=verbose, force=True)
  191. @cmd
  192. def restore(db_name, source_sql, site=None, verbose=True, force=False):
  193. install(db_name, source_sql, site=site, verbose=verbose, force=force)
  194. @cmd
  195. def install_fixtures(site=None):
  196. webnotes.init(site=site)
  197. from webnotes.install_lib.install import install_fixtures
  198. install_fixtures()
  199. webnotes.destroy()
  200. @cmd
  201. def add_system_manager(email, first_name=None, last_name=None, site=None):
  202. webnotes.connect(site=site)
  203. webnotes.profile.add_system_manager(email, first_name, last_name)
  204. webnotes.conn.commit()
  205. webnotes.destroy()
  206. @cmd
  207. def make_demo(site=None):
  208. import utilities.demo.make_demo
  209. webnotes.init(site=site)
  210. utilities.demo.make_demo.make()
  211. webnotes.destroy()
  212. @cmd
  213. def make_demo_fresh(site=None):
  214. import utilities.demo.make_demo
  215. webnotes.init(site=site)
  216. utilities.demo.make_demo.make(reset=True)
  217. webnotes.destroy()
  218. # utilities
  219. @cmd
  220. def update(remote=None, branch=None, site=None, reload_gunicorn=False):
  221. pull(remote=remote, branch=branch, site=site)
  222. # maybe there are new framework changes, any consequences?
  223. reload(webnotes)
  224. if not site: build()
  225. latest(site=site)
  226. if reload_gunicorn:
  227. import subprocess
  228. subprocess.check_output("killall -HUP gunicorn".split())
  229. @cmd
  230. def latest(site=None, verbose=True):
  231. import webnotes.modules.patch_handler
  232. import webnotes.model.sync
  233. import webnotes.plugins
  234. webnotes.connect(site=site)
  235. try:
  236. # run patches
  237. webnotes.local.patch_log_list = []
  238. webnotes.modules.patch_handler.run_all()
  239. if verbose:
  240. print "\n".join(webnotes.local.patch_log_list)
  241. # sync
  242. webnotes.model.sync.sync_all()
  243. # remove __init__.py from plugins
  244. webnotes.plugins.remove_init_files()
  245. except webnotes.modules.patch_handler.PatchError, e:
  246. print "\n".join(webnotes.local.patch_log_list)
  247. raise
  248. finally:
  249. webnotes.destroy()
  250. @cmd
  251. def sync_all(site=None, force=False):
  252. import webnotes.model.sync
  253. webnotes.connect(site=site)
  254. webnotes.model.sync.sync_all(force=force)
  255. webnotes.destroy()
  256. @cmd
  257. def patch(patch_module, site=None, force=False):
  258. import webnotes.modules.patch_handler
  259. webnotes.connect(site=site)
  260. webnotes.local.patch_log_list = []
  261. webnotes.modules.patch_handler.run_single(patch_module, force=force)
  262. print "\n".join(webnotes.local.patch_log_list)
  263. webnotes.destroy()
  264. @cmd
  265. def update_all_sites(remote=None, branch=None, verbose=True):
  266. pull(remote, branch)
  267. # maybe there are new framework changes, any consequences?
  268. reload(webnotes)
  269. build()
  270. for site in get_sites():
  271. latest(site=site, verbose=verbose)
  272. @cmd
  273. def reload_doc(module, doctype, docname, site=None, force=False):
  274. webnotes.connect(site=site)
  275. webnotes.reload_doc(module, doctype, docname, force=force)
  276. webnotes.destroy()
  277. @cmd
  278. def build():
  279. import webnotes.build
  280. webnotes.build.bundle(False)
  281. @cmd
  282. def watch():
  283. import webnotes.build
  284. webnotes.build.watch(True)
  285. @cmd
  286. def backup(site=None, with_files=False, verbose=True, backup_path_db=None, backup_path_files=None):
  287. from webnotes.utils.backups import scheduled_backup
  288. webnotes.connect(site=site)
  289. odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files)
  290. if verbose:
  291. from webnotes.utils import now
  292. print "database backup taken -", odb.backup_path_db, "- on", now()
  293. if with_files:
  294. print "files backup taken -", odb.backup_path_files, "- on", now()
  295. webnotes.destroy()
  296. return odb
  297. @cmd
  298. def move(site=None, dest_dir=None):
  299. import os
  300. if not dest_dir:
  301. raise Exception, "--dest_dir is required for --move"
  302. dest_dir = dest_dir[0]
  303. if not os.path.isdir(dest_dir):
  304. raise Exception, "destination is not a directory or does not exist"
  305. webnotes.init(site=site)
  306. old_path = webnotes.utils.get_site_path()
  307. new_path = os.path.join(dest_dir, site)
  308. # check if site dump of same name already exists
  309. site_dump_exists = True
  310. count = 0
  311. while site_dump_exists:
  312. final_new_path = new_path + (count and str(count) or "")
  313. site_dump_exists = os.path.exists(final_new_path)
  314. count = int(count or 0) + 1
  315. os.rename(old_path, final_new_path)
  316. webnotes.destroy()
  317. return os.path.basename(final_new_path)
  318. @cmd
  319. def docs():
  320. from core.doctype.documentation_tool.documentation_tool import write_static
  321. write_static()
  322. @cmd
  323. def domain(host_url=None, site=None):
  324. webnotes.connect(site=site)
  325. if host_url:
  326. webnotes.conn.set_value("Website Settings", None, "subdomain", host_url)
  327. webnotes.conn.commit()
  328. else:
  329. print webnotes.conn.get_value("Website Settings", None, "subdomain")
  330. webnotes.destroy()
  331. @cmd
  332. def make_conf(db_name=None, db_password=None, site=None, site_config=None):
  333. from webnotes.install_lib.install import make_conf
  334. make_conf(db_name=db_name, db_password=db_password, site=site, site_config=site_config)
  335. @cmd
  336. def make_custom_server_script(doctype, site=None):
  337. from core.doctype.custom_script.custom_script import make_custom_server_script_file
  338. webnotes.connect(site=site)
  339. make_custom_server_script_file(doctype)
  340. webnotes.destroy()
  341. # clear
  342. @cmd
  343. def clear_cache(site=None):
  344. import webnotes.sessions
  345. webnotes.connect(site=site)
  346. webnotes.sessions.clear_cache()
  347. webnotes.destroy()
  348. @cmd
  349. def clear_web(site=None):
  350. import webnotes.webutils
  351. webnotes.connect(site=site)
  352. webnotes.webutils.clear_cache()
  353. webnotes.destroy()
  354. @cmd
  355. def reset_perms(site=None):
  356. webnotes.connect(site=site)
  357. for d in webnotes.conn.sql_list("""select name from `tabDocType`
  358. where ifnull(istable, 0)=0 and ifnull(custom, 0)=0"""):
  359. webnotes.clear_cache(doctype=d)
  360. webnotes.reset_perms(d)
  361. webnotes.destroy()
  362. # scheduler
  363. @cmd
  364. def run_scheduler(site=None):
  365. import webnotes.utils.scheduler
  366. webnotes.connect(site=site)
  367. print webnotes.utils.scheduler.execute()
  368. webnotes.destroy()
  369. @cmd
  370. def run_scheduler_event(event, site=None):
  371. import webnotes.utils.scheduler
  372. webnotes.connect(site=site)
  373. print webnotes.utils.scheduler.trigger("execute_" + event)
  374. webnotes.destroy()
  375. # replace
  376. @cmd
  377. def replace(search_regex, replacement, extn, force=False):
  378. print search_regex, replacement, extn
  379. replace_code('.', search_regex, replacement, extn, force=force)
  380. # import/export
  381. @cmd
  382. def export_doc(doctype, docname, site=None):
  383. import webnotes.modules
  384. webnotes.connect(site=site)
  385. webnotes.modules.export_doc(doctype, docname)
  386. webnotes.destroy()
  387. @cmd
  388. def export_doclist(doctype, name, path, site=None):
  389. from core.page.data_import_tool import data_import_tool
  390. webnotes.connect(site=site)
  391. data_import_tool.export_json(doctype, name, path)
  392. webnotes.destroy()
  393. @cmd
  394. def export_csv(doctype, path, site=None):
  395. from core.page.data_import_tool import data_import_tool
  396. webnotes.connect(site=site)
  397. data_import_tool.export_csv(doctype, path)
  398. webnotes.destroy()
  399. @cmd
  400. def import_doclist(path, site=None, force=False):
  401. from core.page.data_import_tool import data_import_tool
  402. webnotes.connect(site=site)
  403. data_import_tool.import_doclist(path, overwrite=force)
  404. webnotes.destroy()
  405. # translation
  406. @cmd
  407. def build_message_files(site=None):
  408. import webnotes.translate
  409. webnotes.connect(site=site)
  410. webnotes.translate.build_message_files()
  411. webnotes.destroy()
  412. @cmd
  413. def export_messages(lang, outfile, site=None):
  414. import webnotes.translate
  415. webnotes.connect(site=site)
  416. webnotes.translate.export_messages(lang, outfile)
  417. webnotes.destroy()
  418. @cmd
  419. def import_messages(lang, infile, site=None):
  420. import webnotes.translate
  421. webnotes.connect(site=site)
  422. webnotes.translate.import_messages(lang, infile)
  423. webnotes.destroy()
  424. @cmd
  425. def google_translate(lang, infile, outfile, site=None):
  426. import webnotes.translate
  427. webnotes.connect(site=site)
  428. webnotes.translate.google_translate(lang, infile, outfile)
  429. webnotes.destroy()
  430. @cmd
  431. def translate(lang, site=None):
  432. import webnotes.translate
  433. webnotes.connect(site=site)
  434. webnotes.translate.translate(lang)
  435. webnotes.destroy()
  436. # git
  437. @cmd
  438. def git(param):
  439. if isinstance(param, (list, tuple)):
  440. param = " ".join(param)
  441. import os
  442. os.system("""cd lib && git %s""" % param)
  443. os.system("""cd app && git %s""" % param)
  444. def get_remote_and_branch(remote=None, branch=None):
  445. if not (remote and branch):
  446. webnotes.init()
  447. if not webnotes.conf.branch:
  448. raise Exception("Please specify remote and branch")
  449. remote = remote or "origin"
  450. branch = branch or webnotes.conf.branch
  451. webnotes.destroy()
  452. return remote, branch
  453. @cmd
  454. def pull(remote=None, branch=None):
  455. remote, branch = get_remote_and_branch(remote, branch)
  456. git(("pull", remote, branch))
  457. @cmd
  458. def push(remote=None, branch=None):
  459. remote, branch = get_remote_and_branch(remote, branch)
  460. git(("push", remote, branch))
  461. @cmd
  462. def status():
  463. git("status")
  464. @cmd
  465. def commit(message):
  466. git("""commit -a -m "%s" """ % message.replace('"', '\"'))
  467. @cmd
  468. def checkout(branch):
  469. git(("checkout", branch))
  470. @cmd
  471. def set_admin_password(admin_password, site=None):
  472. import webnotes
  473. webnotes.connect(site=site)
  474. webnotes.conn.sql("""update __Auth set `password`=password(%s)
  475. where user='Administrator'""", (admin_password,))
  476. webnotes.conn.commit()
  477. webnotes.destroy()
  478. @cmd
  479. def mysql(site=None):
  480. import webnotes
  481. import commands, os
  482. msq = commands.getoutput('which mysql')
  483. webnotes.init(site=site)
  484. os.execv(msq, [msq, '-u', webnotes.conf.db_name, '-p'+webnotes.conf.db_password, webnotes.conf.db_name, '-h', webnotes.conf.db_host or "localhost"])
  485. webnotes.destroy()
  486. @cmd
  487. def python(site=None):
  488. import webnotes
  489. import commands, os
  490. python = commands.getoutput('which python')
  491. webnotes.init(site=site)
  492. if site:
  493. os.environ["site"] = site
  494. os.environ["PYTHONSTARTUP"] = os.path.join(os.path.dirname(__file__), "pythonrc.py")
  495. os.execv(python, [python])
  496. webnotes.destroy()
  497. @cmd
  498. def smtp_debug_server():
  499. import commands, os
  500. python = commands.getoutput('which python')
  501. os.execv(python, [python, '-m', "smtpd", "-n", "-c", "DebuggingServer", "localhost:25"])
  502. @cmd
  503. def serve(port=8000):
  504. import webnotes.app
  505. webnotes.app.serve(port=port)
  506. def replace_code(start, txt1, txt2, extn, search=None, force=False):
  507. """replace all txt1 by txt2 in files with extension (extn)"""
  508. import webnotes.utils
  509. import os, re
  510. esc = webnotes.utils.make_esc('[]')
  511. if not search: search = esc(txt1)
  512. for wt in os.walk(start, followlinks=1):
  513. for fn in wt[2]:
  514. if fn.split('.')[-1]==extn:
  515. fpath = os.path.join(wt[0], fn)
  516. with open(fpath, 'r') as f:
  517. content = f.read()
  518. if re.search(search, content):
  519. res = search_replace_with_prompt(fpath, txt1, txt2, force)
  520. if res == 'skip':
  521. return 'skip'
  522. def search_replace_with_prompt(fpath, txt1, txt2, force=False):
  523. """ Search and replace all txt1 by txt2 in the file with confirmation"""
  524. from termcolor import colored
  525. with open(fpath, 'r') as f:
  526. content = f.readlines()
  527. tmp = []
  528. for c in content:
  529. if c.find(txt1) != -1:
  530. print fpath
  531. print colored(txt1, 'red').join(c[:-1].split(txt1))
  532. a = ''
  533. if force:
  534. c = c.replace(txt1, txt2)
  535. else:
  536. while a.lower() not in ['y', 'n', 'skip']:
  537. a = raw_input('Do you want to Change [y/n/skip]?')
  538. if a.lower() == 'y':
  539. c = c.replace(txt1, txt2)
  540. elif a.lower() == 'skip':
  541. return 'skip'
  542. tmp.append(c)
  543. with open(fpath, 'w') as f:
  544. f.write(''.join(tmp))
  545. print colored('Updated', 'green')
  546. @cmd
  547. def get_site_status(site=None, verbose=False):
  548. import webnotes
  549. import webnotes.utils
  550. from webnotes.profile import get_system_managers
  551. from core.doctype.profile.profile import get_total_users, get_active_users, \
  552. get_website_users, get_active_website_users
  553. import json
  554. webnotes.connect(site=site)
  555. ret = {
  556. 'last_backup_on': webnotes.local.conf.last_backup_on,
  557. 'active_users': get_active_users(),
  558. 'total_users': get_total_users(),
  559. 'active_website_users': get_active_website_users(),
  560. 'website_users': get_website_users(),
  561. 'system_managers': "\n".join(get_system_managers()),
  562. 'default_company': webnotes.conn.get_default("company"),
  563. 'disk_usage': webnotes.utils.get_disk_usage(),
  564. 'working_directory': webnotes.utils.get_base_path()
  565. }
  566. # country, timezone, industry
  567. control_panel_details = webnotes.conn.get_value("Control Panel", "Control Panel",
  568. ["country", "time_zone", "industry"], as_dict=True)
  569. if control_panel_details:
  570. ret.update(control_panel_details)
  571. # basic usage/progress analytics
  572. for doctype in ("Company", "Customer", "Item", "Quotation", "Sales Invoice",
  573. "Journal Voucher", "Stock Ledger Entry"):
  574. key = doctype.lower().replace(" ", "_") + "_exists"
  575. ret[key] = 1 if webnotes.conn.count(doctype) else 0
  576. webnotes.destroy()
  577. if verbose:
  578. print json.dumps(ret, indent=1, sort_keys=True)
  579. return ret
  580. @cmd
  581. def update_site_config(site_config, site, verbose=False):
  582. import json
  583. if isinstance(site_config, basestring):
  584. site_config = json.loads(site_config)
  585. webnotes.init(site=site)
  586. webnotes.conf.site_config.update(site_config)
  587. site_config_path = webnotes.get_conf_path(webnotes.conf.sites_dir, site)
  588. with open(site_config_path, "w") as f:
  589. json.dump(webnotes.conf.site_config, f, indent=1, sort_keys=True)
  590. webnotes.destroy()
  591. if __name__=="__main__":
  592. main()