Construct the .epub file
161246
function _bundleEPUB(config, done) {
    
    var epubconfig = config.akashacmsEPUB;
    
    var archive = archiver('zip');
    
    var output = fs.createWriteStream(config.akashacmsEPUB.bookmetadata.epub);
            
    output.on('close', function() {
        logger.info(archive.pointer() + ' total bytes');
        logger.info('archiver has been finalized and the output file descriptor has closed.');
        done();
    });
    
    archive.on('error', function(err) {
      logger.info('*********** BundleEPUB ERROR '+ err);
      done(err);
    });
    
    archive.pipe(output);
    
    // The mimetype file must be the first entry, and must not be compressed
    archive.append(
        fs.createReadStream(path.join(config.root_out, "mimetype")),
        { name: "mimetype", store: true });
    archive.append(
        fs.createReadStream(path.join(config.root_out, "META-INF", "container.xml")),
        { name: path.join("META-INF", "container.xml") });
    archive.append(
        fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.bookmetadata.opf)),
        { name: config.akashacmsEPUB.bookmetadata.opf });
    // archive.append(
    //     fs.createReadStream(path.join(config.root_out, config.akashacmsEPUB.files.ncx)),
    //    { name: config.akashacmsEPUB.files.ncx });
    
    // logger.info(util.inspect(config.akashacmsEPUB.manifest));
    async.eachSeries(config.akashacmsEPUB.manifest,
        function(item, next) {
            // logger.info(util.inspect(item));
            // if (item.spinetoc !== true) { // this had been used to skip the NCX file
            archive.append(
                fs.createReadStream(path.join(config.root_out, item.href)),
                { name: item.href }
            );
            // }
            next();
        },
        function(err) {
            if (err) logger.error(err);
            logger.info('before finalize');
            archive.finalize();
        });
}
220849
function runEbookConvert(output) {
    var logger = output.getLogger();
    var options = output.getOptions();
    var format = options.get('format');
    var outputFolder = output.getRoot();

    if (!format) {
        return Promise(output);
    }

    return getConvertOptions(output)
    .then(function(options) {
        var cmd = [
            'ebook-convert',
            path.resolve(outputFolder, SUMMARY_FILE),
            path.resolve(outputFolder, 'index.' + format),
            command.optionsToShellArgs(options)
        ].join(' ');

        return command.exec(cmd)
        .progress(function(data) {
            logger.debug(data);
        })
        .fail(function(err) {
            if (err.code == 127) {
                throw error.RequireInstallError({
                    cmd: 'ebook-convert',
                    install: 'Install it from Calibre: https://calibre-ebook.com'
                });
            }

            throw error.EbookError(err);
        });
    })
    .thenResolve(output);
}
918930
function (exec) {
      var _exec = ["pandoc"],
          conf = this.configs;

      _exec.push("-S");
      _exec.push("-o " + conf.target);
      _exec.push("--epub-metadata="   + conf.metadata);
      _exec.push("--epub-stylesheet=" + conf.stylesheet);
      _exec.push("--epub-cover-image=" + conf.cover);

      _exec.push(this.files["chapters"].join(" "));

      exec.push(_exec.join(" "));

      return exec;
    }
325405
def generate(env):
    """"""

    env.SetDefault(
        # Default names for customized XSL stylesheets
        DOCBOOK_DEFAULT_XSL_EPUB = '',
        DOCBOOK_DEFAULT_XSL_HTML = '',
        DOCBOOK_DEFAULT_XSL_HTMLCHUNKED = '',
        DOCBOOK_DEFAULT_XSL_HTMLHELP = '',
        DOCBOOK_DEFAULT_XSL_PDF = '',
        DOCBOOK_DEFAULT_XSL_MAN = '',
        DOCBOOK_DEFAULT_XSL_SLIDESPDF = '',
        DOCBOOK_DEFAULT_XSL_SLIDESHTML = '',
        
        # Paths to the detected executables
        DOCBOOK_XSLTPROC = '',
        DOCBOOK_XMLLINT = '',
        DOCBOOK_FOP = '',
        
        # Additional flags for the text processors
        DOCBOOK_XSLTPROCFLAGS = SCons.Util.CLVar(''),
        DOCBOOK_XMLLINTFLAGS = SCons.Util.CLVar(''),
        DOCBOOK_FOPFLAGS = SCons.Util.CLVar(''),
        DOCBOOK_XSLTPROCPARAMS = SCons.Util.CLVar(''),
        
        # Default command lines for the detected executables
        DOCBOOK_XSLTPROCCOM = xsltproc_com['xsltproc'],
        DOCBOOK_XMLLINTCOM = xmllint_com['xmllint'],
        DOCBOOK_FOPCOM = fop_com['fop'],

        # Screen output for the text processors
        DOCBOOK_XSLTPROCCOMSTR = None,
        DOCBOOK_XMLLINTCOMSTR = None,
        DOCBOOK_FOPCOMSTR = None,
        
        )
    _detect(env)

    env.AddMethod(DocbookEpub, "DocbookEpub")
    env.AddMethod(DocbookHtml, "DocbookHtml")
    env.AddMethod(DocbookHtmlChunked, "DocbookHtmlChunked")
    env.AddMethod(DocbookHtmlhelp, "DocbookHtmlhelp")
    env.AddMethod(DocbookPdf, "DocbookPdf")
    env.AddMethod(DocbookMan, "DocbookMan")
    env.AddMethod(DocbookSlidesPdf, "DocbookSlidesPdf")
    env.AddMethod(DocbookSlidesHtml, "DocbookSlidesHtml")
    env.AddMethod(DocbookXInclude, "DocbookXInclude")
    env.AddMethod(DocbookXslt, "DocbookXslt")
205048
def create_book(self, name):
        """"""
        name = name.strip()
        if not len(name):
            self.error("Cannot have a blank book name")
        # The next could be relaxed, if users want commas in book names, but
        # I prefer to keep it, in case later there could be a syntax for multiple
        # book names, using comma.
        if name.find(",") >= 0:
            self.error("Cannot have a ',' in a book name")
        existing = self.list_books()
        nexisting = len(existing)
        if name in existing:
            self.error("Already have a book named '%s'" % name)
        try:
            self.cur.execute("INSERT INTO book (number, name) VALUES(?, ?);", (nexisting, name))
            self.con.commit()
        except:
            self.fyi("Error adding a book named '%s'" % name)
1302343
def make_lib(self, version):
        
        if os.path.exists(POETRY_LIB_BACKUP):
            shutil.rmtree(POETRY_LIB_BACKUP)

        # Backup the current installation
        if os.path.exists(POETRY_LIB):
            shutil.copytree(POETRY_LIB, POETRY_LIB_BACKUP)
            shutil.rmtree(POETRY_LIB)

        try:
            self._make_lib(version)
        except Exception:
            if not os.path.exists(POETRY_LIB_BACKUP):
                raise

            shutil.copytree(POETRY_LIB_BACKUP, POETRY_LIB)
            shutil.rmtree(POETRY_LIB_BACKUP)

            raise
        finally:
            if os.path.exists(POETRY_LIB_BACKUP):
                shutil.rmtree(POETRY_LIB_BACKUP)
874481
def _removeSpecialCharacters(epub):
    
    special_chars = "/:,- "

    epub_dict = epub._asdict()

    for key in epub_dict.keys():
        if isinstance(epub_dict[key], basestring):
            epub_dict[key] = epub_dict[key].strip(special_chars)

        elif type(epub_dict[key]) in [tuple, list]:
            out = []
            for item in epub_dict[key]:
                if not isinstance(item, Author):
                    out.append(item)
                    continue

                new_item = item._asdict()

                for key in new_item.keys():
                    new_item[key] = new_item[key].strip(special_chars)

                out.append(Author(**new_item))

            epub_dict[key] = out

    return EPublication(**epub_dict)
924773
def _main():
    
    from argparse import ArgumentParser, FileType
    from gutenberg import Error
    from gutenberg._util.os import reopen_encoded

    parser = ArgumentParser(description='Download a Project Gutenberg text')
    parser.add_argument('etextno', type=int)
    parser.add_argument('outfile', type=FileType('w'))
    parser.add_argument('--mirror', '-m', type=str, default=None)
    parser.add_argument('--prefer-ascii', '-a', type=bool, default=False)
    args = parser.parse_args()

    try:
        text = load_etext(args.etextno,
                          mirror=args.mirror,
                          prefer_ascii=args.prefer_ascii)
        with reopen_encoded(args.outfile, 'w', 'utf8') as outfile:
            outfile.write(text)
    except Error as error:
        parser.error(str(error))
599714
def _docx_to_epub(
            self):
        
        self.log.debug('starting the ``_docx_to_epub`` method')

        if self.footer:
            footer = self._tmp_html_file(self.footer)
            footer = '"%(footer)s"' % locals()
        else:
            footer = ""

        if self.header:
            header = self._tmp_html_file(self.header)
            header = '"%(header)s"' % locals()
        else:
            header = ""

        # FIRST CONVERT THE DOC TO HTML
        docx = self.urlOrPath

        if self.title:
            title = self.title.replace(".html", "")
            html = "/tmp/" + self.title.replace(".html", "") + ".html"
        else:
            title = os.path.basename(docx).replace(
                ".docx", "").replace("_", " ")
            html = "/tmp/" + os.path.basename(docx).replace(".docx", ".html")
        pandoc = self.settings["executables"]["pandoc"]

        # TMP IMAGE DIR
        now = datetime.now()
        now = now.strftime("%Y%m%dt%H%M%S")
        imageDir = "/tmp/%(now)s" % locals()
        if not os.path.exists(imageDir):
            os.makedirs(imageDir)
        cmd = """%(pandoc)s --extract-media=%(imageDir)s -t html -f docx '%(docx)s' -o '%(html)s' """ % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        stdout, stderr = p.communicate()
        self.log.debug('output: %(stdout)s' % locals())

        try:
            with open(html):
                pass
            fileExists = True
        except IOError:
            fileExists = False
            self.log.error(
                "the html %s does not exist on this machine, here is the failure message: %s" % (html, stderr))
            try:
                shutil.rmtree(imageDir)
            except:
                pass
            return None

        if fileExists:
            if self.outputDirectory:
                epub = self.outputDirectory + "/" + \
                    os.path.basename(html).replace(".html", ".epub")
            else:
                epub = docx.replace(".docx", ".epub")
            pandoc = self.settings["executables"]["pandoc"]

            cmd = """%(pandoc)s --metadata=title:'%(title)s' -S -s -f html -t epub3 %(header)s '%(html)s' %(footer)s -o '%(epub)s' """ % locals(
            )
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
            stdout, stderr = p.communicate()
            self.log.debug('output: %(stdout)s' % locals())

            try:
                shutil.rmtree(imageDir)
                os.remove(html)
            except:
                pass

            try:
                with open(epub):
                    pass
                fileExists = True
            except IOError:
                fileExists = False
                self.log.error(
                    "the epub %s does not exist on this machine, here is the failure message: %s" % (epub, stderr))
                return None

        self.log.debug('completed the ``_docx_to_epub`` method')
        return epub
176848
def EBook(self, data=None, subset=None):
        """"""
        return self.factory.get_object(jssobjects.EBook, data, subset)
629504
def check(self):
        ""
        config = self.load_config()
        if not check_dependency_epubcheck():
            sys.exit(error('Unavailable command.'))
        epub_file = u"%s.epub" % config['fileroot']
        epub_path = join(CWD, 'build', epub_file)
        print success("Starting to check %s..." % epub_file)
        epubcheck = u'epubcheck %s' % epub_path
        epubcheck = shell(epubcheck.encode())
        for line in epubcheck.errors():
            print error(line)
        for line in epubcheck.output():
            print line
661636
def from_comm(cls, pub):
        '''
        
        '''
        filename = None
        if pub.b64_data:
            filename = cls._save_to_unique_filename(pub)

        return cls(
            isbn=pub.isbn,
            uuid=pub.uuid,
            aleph_id=pub.aleph_id,

            dir_pointer=filename
        )
498000
def source_start(base='', book_id='book'):
    
    repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id)
    possible_paths = ["book.asciidoc",
                      repo_htm_path,
                      "{}-0.txt".format(book_id),
                      "{}-8.txt".format(book_id),
                      "{}.txt".format(book_id),
                      "{}-pdf.pdf".format(book_id),
                     ]

    # return the first match

    for path in possible_paths:
        fullpath = os.path.join(base, path)
        if os.path.exists(fullpath):
            return path

    return None
703334
def load_abgfiles(dir=None):
    """"""
    import ephem,string
    if dir is None:
        import tkFileDialog
	try: 
            dir=tkFileDialog.askdirectory()
        except:
            return
    if dir is None:
        return None
    from glob import glob
    files=glob(dir+"/*.abg")
    import os
    for f in files:
        (name,ext)=os.path.splitext(os.path.basename(f))
	NAME=name.strip().upper()
	kbos[name]=f
	#print name
        aei=file(dir+"/"+name+".aei")
        lines=aei.readlines()
        aei.close()
        objInfoDict[name]="%6s %6s %6s\n" % ( string.center("a",6),
				            string.center("e",6),
	 				    string.center("i",6) ) 
        try:
          (a,e,i,N,w,T) = lines[4].split()
        except:
          print lines[4]
          (a,e,i,N,w,T) = (0,0,0,0,0,0)
        objInfoDict[name]+="%6.2f %6.3f %6.2f\n" % (float(a),float(e),float(i))
        s=lines[5][0:2]
        (a,e,i,N,w,T) = lines[5][2:-1].split()
        objInfoDict[name]+=" %6.3f %6.3f %6.3f\n" % (float(a),float(e),float(i))
        abg = file(dir+"/"+name+".abg")
        lines = abg.readlines()
        abg.close()
	for line in lines:
	    if not line[0:5] == "# Bar":
	        continue
            objInfoDict[name]+=line[2:-1]+"\n"
            break
        res=file(dir+"/"+name+".res")
        lines=res.readlines()
        res.close()
        line=lines.pop()
        values=line.split()
        s = "[nobs: "+values[0]+" dt: "+values[1]+"]\n"
        objInfoDict[name]+=s
        mpc = file(dir+"/../mpc/"+name+".mpc")
        lines=mpc.readlines()
        mpc.close()
	last_date=0
	for line in lines:
	    if len(line)==0:
		continue
	    if line[0]=="#":
		continue
            this_year=int(line[15:19])
            this_month=int(line[20:22])
            this_day = int(line[23:25])
	    this_date =  this_year+this_month/12.0 +this_day/365.25
	    if last_date < this_date:
		last_date=this_date
		year=this_year
		day = this_day
		month=this_month	
        mag={}
        for line in lines:
            try:
                mags=line[65:69].strip()
		if len(mags)==0:
		    continue
                filter=line[70]
	        if filter not in mag:
                    mag[filter]=[]
                mag[filter].append(float(mags)) 
	    except:
	        continue
        mags=''
        for filter in mag:
	    magv=0
 	    for m in mag[filter]:
	        magv = magv+m/len(mag[filter]) 
            mags = mags+ "%4.1f-%s " % ( magv , filter)
        if len(mags)==0:
	    mags= "N/A"
        objInfoDict[name]+="MAG: "+mags+"\n"
        objInfoDict[name]+="Last obs: %s %s %s \n" % (year,month, day)

    doplot(kbos)
801054
def get(self):
        
        self.log.debug('starting the ``get`` method')

        if self.format == "epub":
            if self.urlOrPath[:4] == "http" or self.urlOrPath[:4] == "www.":
                ebook = self._url_to_epub()
            elif ".docx" in self.urlOrPath:
                ebook = self._docx_to_epub()

        if self.format == "mobi":
            if self.urlOrPath[:4] == "http" or self.urlOrPath[:4] == "www.":
                epub = self._url_to_epub()
            elif ".docx" in self.urlOrPath:
                epub = self._docx_to_epub()

            if not epub:
                return None

            ebook = self._epub_to_mobi(
                epubPath=epub,
                deleteEpub=False
            )

        tag(
            log=self.log,
            filepath=ebook,
            tags=False,
            rating=False,
            wherefrom=self.url
        )

        self.log.debug('completed the ``get`` method')
        return ebook
505857
def produce(epubfile, basedir = nil, tmpdir = nil)
      current = Dir.pwd
      basedir ||= current

      new_tmpdir = tmpdir.nil? ? Dir.mktmpdir : tmpdir
      if epubfile !~ %r{\A/}
        epubfile = "#{current}/#{epubfile}"
      end

      # FIXME: error check
      File.unlink(epubfile) if File.exist?(epubfile)

      begin
        @epub.produce(epubfile, basedir, new_tmpdir)
      ensure
        FileUtils.rm_r(new_tmpdir) if tmpdir.nil?
      end
    end
519897
def abook_file(vcard, bookfile):
        """"""
        book = ConfigParser(default_section='format')

        book['format'] = {}
        book['format']['program'] = 'abook'
        book['format']['version'] = '0.6.1'

        for (i, card) in enumerate(readComponents(vcard.read())):
            Abook.to_abook(card, str(i), book, bookfile)
        with open(bookfile, 'w') as fp:
            book.write(fp, False)