Action

Save all to iCloud Drive

Posted by RoyRogers, Last update about 1 month ago

This will save all drafts to the Drafts folder in iCloud
- Gets file name from “safe_title - created date”:
- file name = “title - yyyy-mm-dd_hhmm”,
- so updated drafts overwrite old versions.

Steps

  • script

    // Save all to iCloud drive
    // Only updates new and modified since last run.
    // RV 2020-05-16 at 17:05 EDT
    
    // Gets file name from "safe_title - created date",
    // so in case of duplicate titles,
    // updated drafts overwrites old version only.
    
    'use strict';
    
    let ts_file = '/.save_all_time_stamp.txt'
    let box = 'all';
    
    (() => {
      const now = new Date();
      const ts = now.toString("yyyyMMddHHmmss");
      let fm = FileManager.createCloud();
      let lastime = Number(fm.read(ts_file));
    
      if (isNaN(lastime)) {
        lastime = 0;
      }
    
      console.log('Save all to iCloud');
      let count = 0;
      let drafts = Draft.query("", box);
      for(let d of drafts) {
        let mod = Number(d.modifiedAt.toString("yyyyMMddHHmmss"));
        
        if (mod < lastime) {
          continue;
        }
        
        let content= d.processTemplate("[[draft]]").trim();
        if (!content) continue;
        let title = d.processTemplate("[[safe_title]]").slice(0, 60);
        let created = d.processTemplate("[[created|%Y-%m-%d_%H%M]]");
        let tags = d.processTemplate("[[tags]]");
        
        if (tags != '') {
          content += '\n\n#' + tags.replace(/,/g, ' #');
        }
        
        let type = 'md';
        let ext = 'md';
        
        if (d.languageGrammar == 'JavaScript') {
          type = 'script';
          ext = 'js';
        } else if (!d.languageGrammar.endsWith('Markdown')) {
          type = 'text';
          ext = 'txt';
        }
        
        let path = `/Drafts_${type}/${title} - ${created}.${ext}`;
        try {
          let success = fm.writeString(path, content);
          fm.setCreationDate(path, d.createdAt)
          fm.setModificationDate(path, d.modifiedAt)
          if (!success) {
            alert(count + ': write failed: ' + path);
            // return;
          }
        } catch(err) {
          alert(err.message);
        }
        count++;
      }
    
      let success = fm.writeString(ts_file, ts);
      // alert(count);
      console.log(count + ' files saved.');
      app.displayInfoMessage(count + ' files saved.');
    })()
    
    

Options

  • After Success Default
    Notification Error
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.