Guest User

Untitled

a guest
Oct 15th, 2018
141
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #! /usr/bin/env python3
  2. # source from  https://gist.github.com/bwiernik/45f514da37af92491893f2f7212710f9  zotxform  v0.612
  3. # AUTHORS: Ian-Mathew Hornburg ‹imhornburg@gmail.com›
  4. #          Optima Language Analytics LLC
  5. # LICENSE: [TBD]
  6. # Copyright (c) 2014–2015, the authors.
  7. # All rights reserved.
  8. # --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- #
  9.  
  10. # update zotero.jar : add a custom plugin to tinymce and modify some files.
  11. # should be run as admin
  12.  
  13.  
  14.  
  15. from shutil import copytree, rmtree, copy2
  16. import logging
  17. import os
  18. import os.path as path
  19. import zipfile as z
  20. from win10toast import ToastNotifier
  21. from subprocess import Popen
  22.  
  23. import time
  24.  
  25. #custom var
  26. icon_start =r"C:\custom_path\MyIcons\start.ico"  #★
  27. icon_end =r"C:\custom_path\MyIcons\done.ico"  #★
  28. customplug_original_path=r"C:\custom_path\Zotero\custom_plugin_folder" #★
  29. TEMPDIR_PATH = r"C:\custom_path\Zotero\temp_dir"#★
  30.  
  31.  
  32.  
  33. # other vars
  34. manifest_path = r"C:\Program Files (x86)\Zotero\chrome.manifest"
  35. manifest_edit = '\n\nEdits added + custom_plugin'  # + date_time
  36. zotero_exe =  r"C:\Program Files (x86)\Zotero\zotero.exe"
  37. archive_path = r"C:\Program Files (x86)\Zotero\zotero.jar"
  38.  
  39. replace_list= [
  40.     {'path':path.join('resource', 'tinymce', 'css', 'note-ui.css'),
  41.     'replacement_table': {
  42.         '.mce-window {\n    width: auto !important;\n   background: none !important;\n}':'.mce-window {\n   width:  300px; /* xedit was set to :   auto !important; */\n    background: none !important;\n  position: fixed;  /* xedit*/\n    top: 0; /* xedit*/\n    right: 0;  /* xedit*/\n}',
  43.         '.mce-window:not([role=alertdialog]) {\n    left: 0 !important;\n}':'/*.mce-window:not([role=alertdialog]) {\n  left: 0 !important;\n} */',
  44.         '.mce-window-head {\n   background: #fff !important;\n}':'.mce-window-head {\n  background: #fff !important;\nopacity: 0.8;\n}',
  45.         '.mce-window-body {\n   background: #fff !important;\n}':'.mce-window-body {\n  background: #fff !important;\nopacity: 0.8;\n}'
  46.         }
  47.     },
  48.     {'path':path.join('resource', 'tinymce', 'note.html'),  
  49.     'replacement_table': {
  50.         'plugins: "autolink,code,contextmenu,directionality,link,lists,paste,searchreplace,textcolor",': '      /********** START of xEDIT    ********* \n\n        plugin custom_plug added to plugins\n\n     fontsizeselect in toolbar1 \n\n     fontsize_formats: "8px 10px 12px 14px 16px 18px"\n\n        *********/\n\n\n\n      plugins: "autolink,code,custom_plug, contextmenu,directionality,link,lists,paste,searchreplace,textcolor",\n\n      fontsize_formats: "8px 10px 12px 14px 16px 18px",'
  51.         },
  52.     },
  53.     {'path':path.join('resource', 'tinymce', 'tinymce.min.js'),
  54.     'replacement_table': {
  55.         'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins':'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q,del,ins,h1, h2, h3, h4, h5, h6',
  56.         'subscript:{inline:"sub"},superscript:{inline:"sup"}':'subscript:{inline:"sub", styles: {fontSize: \'70%\'}},superscript:{inline:"sup",  styles: {fontSize: \'70%\'}}'
  57.         }
  58.     }  
  59. ]
  60.  
  61. date_time = time.strftime("%Y_%m_%d_") + time.strftime("_%H_%M_%S")
  62.  
  63.  
  64. logging.basicConfig(format="[Zotero Edits] {levelname} :: {message}", style='{')
  65. logger = logging.getLogger('Zotero Edits')
  66. logger.setLevel('INFO')
  67. logger.info("Zotero Edits")
  68.  
  69.  
  70. toaster = ToastNotifier()
  71. toaster.show_toast("Starting updating Zotero",
  72.             "zotero_updating.py",
  73.                 icon_path=icon_start,
  74.                 duration=3)
  75.  
  76. #close zotero before update
  77. os.system("TASKKILL /F /IM zotero.exe")
  78. time.sleep(10)
  79.  
  80.  
  81. # apply the modification stored in replacement to the file  cf line 143
  82. def modify_file(file, replacement):
  83.     logger.info(f"start modifying {file}...")
  84.     with open(file, encoding='utf_8', mode='r') as f:
  85.         properties = f.read()
  86.  
  87.     for target in replacement.keys():
  88.         properties = properties.replace(target, replacement.get(target))
  89.  
  90.     with open(file, encoding='utf_8', mode='w') as f:
  91.         f.write(properties)
  92.     logger.info(f"end  modifying {file}!")
  93.  
  94. zotero_archive_path = path.abspath(archive_path)
  95. chrome_manifeste_path = path.abspath(manifest_path)
  96.  
  97. try:
  98.     if os.path.isfile(chrome_manifeste_path):
  99.         logger.info("Manifest found.")
  100.     else:
  101.         raise FileNotFoundError("chrome.manifest file not found.")
  102.  
  103.     with z.ZipFile(zotero_archive_path, mode='r') as archive:
  104.         os.mkdir(TEMPDIR_PATH)
  105.         os.chdir(TEMPDIR_PATH)  #changes  current working directory  to tempdit
  106.  
  107.         # We wanna preserve the exact order of the files in the archive,
  108.         # since for some applications, order matters (e.g., needing to have
  109.         # the chrome.manifest first). So everything that’s going into the
  110.         # archive needs to be explicitly enumerated in this list, starting
  111.         # with the existing contents.
  112.         file_list = archive.namelist()
  113.  
  114.         # Extract and end scope, closing archive
  115.         logger.info('extracting zotero.jar... ')
  116.         archive.extractall()
  117.         logger.info('finish extracting zotero.jar!')
  118.  
  119.  
  120.     # Add edits to chrome_manifeste
  121.     with open(chrome_manifeste_path, encoding='utf_8', mode='r') as manifest:
  122.         s = manifest.read()
  123.     if manifest_edit in s:
  124.         raise ValueError("Manifest already patched.")
  125.     s = s.join([s, manifest_edit])
  126.     logger.info("Writing patched manifest.")
  127.     with open(chrome_manifeste_path, encoding='utf_8', mode='w') as manifest:
  128.         manifest.write(s)
  129.  
  130.  
  131.     # copy the contents of custom_plug to local dir and save the content in file_list
  132.     logger.info("start copying custom_plug...")
  133.     custom_plug_new=path.join('resource', 'tinymce', 'plugins', 'custom_plug')
  134.     copytree(customplug_original_path, custom_plug_new)
  135.     file_list.append(custom_plug_new)  
  136.     for e in [path.join(dirpath, f) for dirpath, dirname, filename in os.walk(custom_plug_new) for f in filename]:
  137.         file_list.append(e)
  138.     logger.info("end copying custom_plug!")
  139.  
  140.     # modify the files according to its replacement_table
  141.     for item in replace_list:
  142.         modify_file(item["path"],item["replacement_table"])
  143.  
  144.     #backup old zotero.jar
  145.     bkp_zotero_archive_path= zotero_archive_path[:-4]+date_time+".jar"  #remove .jar, add date, add .jar
  146.     copy2(zotero_archive_path, bkp_zotero_archive_path)
  147.     logger.info("backup old zotero.jar")
  148.  
  149.     # Truncate and write new archive
  150.     with z.ZipFile(zotero_archive_path, compression=z.ZIP_DEFLATED, mode='w') as archive:  #should be
  151.         for e in file_list:
  152.             archive.write(e)
  153.     logger.info("Done.")
  154.  
  155. finally:
  156.     os.chdir(os.pardir)
  157.     rmtree(TEMPDIR_PATH)
  158.  
  159.  
  160. #reopen zotero
  161. Popen([zotero_exe])
  162.  
  163.  
  164. #notification end
  165. toaster = ToastNotifier()
  166. toaster.show_toast("Finish updating Zotero",
  167.             "zotero_updating.py",
  168.                 icon_path=icon_end,
  169.                 duration=3)
RAW Paste Data