Advertisement
Guest User

Mikko Rnkk

a guest
Mar 5th, 2009
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Zotero.ZotFile = {
  2.    
  3.  
  4.     prefs: null,
  5.     fileMap: {}, //maps collections to their file objects
  6.  
  7.     mergeObserver: {
  8.         observe: function(a, b, c){
  9.             //this should get called when the dynamic overlay loading in createUI is complete.
  10.             //we adjust UI stuff according to preferences here.
  11.             document.getElementById("zotfile-usetags").setAttribute("checked",
  12.                  Zotero.ZotFile.prefs.getBoolPref("useTags").toString());
  13.         }      
  14.     }, 
  15.  
  16.     createUI: function() {
  17.         // Coment from lytero "I can't reference the node where I want to add stuff directly in an overlay because it has no ID,
  18.         // so I'll create the minimum here and dynamically load the overlay."
  19.         var lmenu = document.createElement("toolbarbutton");
  20.         lmenu.setAttribute("id", "zotfile-menu");
  21.         var parentn = document.getElementById("zotero-collections-pane").firstChild.firstChild;
  22.         parentn = document.getElementById("zotero-items-pane").firstChild;
  23.         var zfb = document.createElement("toolbarbutton");
  24.         zfb.setAttribute("id", "zf-button");
  25.         siblingn = document.getElementById("zotero-tb-advanced-search");
  26.         // add the button to start action
  27.         parentn.insertBefore(zfb, siblingn);
  28.         parentn.insertBefore(document.createElement("toolbarseparator"),siblingn);
  29.  
  30.         //load the overlay
  31.         document.loadOverlay("chrome://zotfile/content/zotfile-menu.xul", this.mergeObserver);
  32.     },
  33.    
  34.     getpara: function (para) {
  35.         // Initially this function
  36.         var filetypes=/pdf|doc|txt|rtf/;
  37.         if(para=="filetypes") return(filetypes);
  38.     },
  39.  
  40.  
  41.     init: function () {
  42.         //set up preferences
  43.         this.prefs = Components.classes["@mozilla.org/preferences-service;1"].
  44.                     getService(Components.interfaces.nsIPrefService);
  45.         this.prefs = this.prefs.getBranch("extensions.zotfile.");
  46.        
  47.         //Register event listener to process also automatically attached files
  48.        
  49.        
  50.         this.createUI()
  51.     },
  52.    
  53.     infoWindow: function(main, message, time){
  54.  
  55.           var pw = new (Zotero.ProgressWindow);
  56.           pw.changeHeadline(main);
  57.           if (main=="error") pw.changeHeadline(Zotero.getString("general.errorHasOccurred"));  pw.addDescription(message);
  58.           pw.show();
  59.           pw.startCloseTimer(time);
  60.  
  61.     },
  62.    
  63.     createFilename: function(zitem, rule){
  64.       // get title of selected item
  65.       var title = zitem.getField('title');
  66.    
  67.       // truncnate title after : . and ?
  68.       var truncate = title.search(/:|\.|\?/);
  69.       if(truncate!=-1) var title = title.substr(0,truncate);
  70.       var title_length =  title.length;
  71.       if (title_length>this.prefs.getIntPref("max_titlelength")) var title = title.substr(0,this.prefs.getIntPref("max_titlelength"));
  72.      
  73.       // get journal
  74.       var journal = zitem.getField('publicationTitle');
  75.  
  76.       // get publisher
  77.       var publisher = zitem.getField('publisher');
  78.  
  79.       // get creator and create authors string
  80.       var add_etal=this.prefs.getBoolPref("add_etal");
  81.       var author = "";
  82.       var creators = zitem.getCreators();
  83.       var numauthors = creators.length;
  84.       for (var i=0; i < creators.length; i++) {
  85.         if(creators[i].creatorTypeID!=1) var numauthors=numauthors-1;
  86.       }
  87.       if (numauthors<=this.prefs.getIntPref("max_authors")) var add_etal=0;
  88.       if (numauthors>this.prefs.getIntPref("max_authors")) var numauthors = 1;
  89.       var j=0;
  90.       for (var i=0; i < creators.length; i++) {
  91.         if (j<numauthors & creators[i].creatorTypeID==1) {
  92.           if (author!="") var author = author + "_" + creators[i].ref.lastName;  
  93.           if (author=="") var author = creators[i].ref.lastName;
  94.           var j=j+1;
  95.         }
  96.       }
  97.       if (add_etal==1) var author = author + " et al";
  98.  
  99.       // date
  100.       var year = zitem.getField('date', true).substr(0,4);
  101.  
  102.       // create filename from rule
  103.       var field=0;
  104.       var filename='';
  105.       for (var i=0; i<rule.length; i++) {  
  106.         var char=rule.charAt(i);
  107.         switch (char) {
  108.           case '%':
  109.             var field=1;
  110.           break;
  111.  
  112.           case 'a':
  113.             if (field==1) var filename = filename + author;
  114.             var field=0;
  115.           break;
  116.  
  117.           case 't':
  118.              if (field==1) var filename = filename + title;
  119.              var field=0;
  120.           break;
  121.  
  122.           case 'y':
  123.              if (field==1) var filename = filename + year;
  124.              var field=0;
  125.           break;
  126.  
  127.           case 'j':
  128.              if (field==1) var filename = filename + journal;
  129.              var field=0;
  130.           break;
  131.  
  132.           case 'p':
  133.              if (field==1) var filename = filename + publisher;
  134.              var field=0;
  135.           break;
  136.  
  137.           case 'w':
  138.              if (field==1) {
  139.                 var filename = filename + journal;
  140.                 if(journal=="") var filename = filename + publisher;
  141.              }
  142.              var field=0;
  143.           break;
  144.  
  145.           default: var filename = filename + char;
  146.         }
  147.       }
  148.  
  149.       //var filename =  author + "_" + year + "_" + title;
  150.    
  151.       // Strip potentially invalid characters
  152.       // (code line adopted from Zotero)
  153.       var filename = filename.replace(/[\/\\\?\*:|"<>\.]/g, '');
  154.    
  155.       return(filename);
  156.     },
  157.  
  158.     getFiletype: function(fname){
  159.          var temp = new Array();
  160.          temp = fname.split('.');
  161.          return(temp[temp.length-1].toLowerCase());
  162.     },
  163.  
  164.     lastFileInDir: function(dir_path, rule){
  165.          // create a nslFile Object for the dir
  166.          try {
  167.           var dir = Components.classes["@mozilla.org/file/local;1"].
  168.           createInstance(Components.interfaces.nsILocalFile);
  169.           dir.initWithPath(dir_path);
  170.           var lastfile_date=0;
  171.           var lastfile_path="";
  172.           var success=0;
  173.        
  174.           // go through all the files in the dir
  175.           var i=0;
  176.           var files = dir.directoryEntries;
  177.           while (files.hasMoreElements()) {
  178.             // get one after the other file
  179.           var file = files.getNext();
  180.           file.QueryInterface(Components.interfaces.nsIFile);
  181.             // only look at files which are neither folders not hidden
  182.             if(!file.isDirectory() & !file.isHidden()) {    
  183.              // now we want to check which filetype we are looking at
  184.              // we only want to consider pdfs, docs, ...
  185.              var filetype=this.getFiletype(file.leafName);
  186.              // for whatever reason, rule is not really passed to the function so I just call getpara directly in the line above...
  187.              var type=filetype.search(this.getpara("filetypes"));
  188.               if (type>=0) {  
  189.                 var modtime = file.lastModifiedTime;
  190.                 var i=i+1;
  191.                 // finally, we set lastfile to the file with the most recent modification
  192.                 if (modtime>lastfile_date){
  193.                   var lastfile_date=modtime;
  194.                   lastfile=file;
  195.                   var success=1;
  196.                }
  197.               }
  198.             }
  199.           }
  200.           if (success==1) return(lastfile);
  201.           else return(-1);
  202.  
  203.          } catch (e) {  
  204.             Components.utils.reportError(e);
  205.             return (-2);
  206.          }
  207.        
  208.     },
  209.  
  210.     moveFile: function(file, destination, filename){
  211.         // create a nslFile Object of the destination folder
  212.         var dir = Components.classes["@mozilla.org/file/local;1"].
  213.         createInstance(Components.interfaces.nsILocalFile);
  214.         dir.initWithPath(destination);
  215.      
  216.         // move file to new location  
  217.         file.moveTo(dir, filename);
  218.        
  219.     },
  220.    
  221.     zotfileAction: function(){
  222.         var items = ZoteroPane.getSelectedItems();
  223.         var item = items[0];
  224.  
  225.  
  226.        
  227.         //check whether it really is an bibliographic item (no Attachment, note or collection)
  228.         if (!item.isAttachment() & !item.isCollection() & !item.isNote()) {
  229.            
  230.           // create the new filename from the selected item
  231.           var rename_rule=this.prefs.getCharPref("renameFormat");
  232.           filename=this.createFilename(item, rename_rule);
  233.        
  234.           // get the last modified file from a directory
  235.           lastfile=this.lastFileInDir(this.prefs.getCharPref("source_dir"), this.getpara("filetypes"));
  236.           if(lastfile!=-1 & lastfile!=-2 ) {
  237.             var lastfile_oldpath=lastfile.leafName;
  238.            
  239.             // complete filename with extension and then move the file to destination
  240.             var filetype=this.getFiletype(lastfile.leafName);
  241.             var filename = filename + "." + filetype;
  242.            
  243.             if(confirm("Do you want to rename and link file \'" + lastfile_oldpath + "\' to the currently selected Zotero item?")){
  244.  
  245.                 this.moveFile(lastfile, this.prefs.getCharPref("source_dir"), filename)
  246.  
  247.                 // recreate the lastfile nslFile Object
  248.                 // (for some reason the Attachment is linked to the wrong location without recreation)
  249.                 var lastfile_path=lastfile.path;
  250.                 var lastfile = Components.classes["@mozilla.org/file/local;1"].
  251.                 createInstance(Components.interfaces.nsILocalFile);
  252.                 lastfile.initWithPath(lastfile_path);
  253.  
  254.                 // Attach last file to selected Zotero item
  255.                 Zotero.Attachments.importFromFile(lastfile, item.itemID);
  256.  
  257.                 //Delete the old file that is not longer needed
  258.                 lastfile.remove(false)
  259.                 // Show message
  260.                 this.infoWindow("Zotfile","File \'" + lastfile_oldpath + "\' changed to \'" + lastfile.leafName + "\' and added as an attachment.",8000);
  261.                //output("\nFile " + lastfile.leafName + " moved to " + dest_dir + filename + " and added as Zotero attachment.\n\n");
  262.             }
  263.           }
  264.           else this.infoWindow("Zotfile Error","Unable to find file in " + this.prefs.getCharPref("source_dir"),8000);
  265.         }
  266.         else this.infoWindow("Zotfile Error","Selected item is either an attachment, a note, or a collection.",8000);
  267.     }
  268.  
  269.  
  270. };
  271.  
  272. // Initialize the utility
  273. window.addEventListener('load', function(e) { Zotero.ZotFile.init(); }, false);
  274.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement