示例#1
0
 def GET(self):
     username = web.input().get("u")
     url = web.input().get("url")
     subject = web.input().get("subject")
     to = web.input().get("to")
     language = web.input().get("lng")
     keepimage = bool(web.input().get("keepimage") == '1')
     booktype = web.input().get("type", "mobi")
     tz = int(web.input().get("tz", TIMEZONE))
     if not all((username,url,subject,to,language,booktype,tz)):
         return "Some parameter missing!<br />"
     
     book = BaseUrlBook()
     book.title = book.description = subject
     book.language = language
     book.keep_image = keepimage
     book.network_timeout = 60
     book.feeds = [(subject,url)]
     book.url_filters = [flt.url for flt in UrlFilter.all()]
     
     opts = oeb = None
     
     # 创建 OEB
     global log
     opts = getOpts()
     oeb = CreateOeb(log, None, opts)
     
     setMetaData(oeb, subject, language, local_time(tz=tz), pubtype='book:book:KindleEar')
     oeb.container = ServerContainer(log)
     
     # 对于html文件,变量名字自文档
     # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
     itemcnt = 0
     for sec_or_media, url, title, content, brief in book.Items(opts):
         if sec_or_media.startswith(r'image/'):
             id, href = oeb.manifest.generate(id='img', href=title)
             item = oeb.manifest.add(id, href, sec_or_media, data=content)
             itemcnt += 1
         else:
             id, href = oeb.manifest.generate(id='page', href='page.html')
             item = oeb.manifest.add(id, href, 'application/xhtml+xml', data=content)
             oeb.spine.add(item, False)
             oeb.toc.add(title, href)
             itemcnt += 1
         
     if itemcnt > 0:
         oIO = byteStringIO()
         o = EPUBOutput() if booktype == "epub" else MOBIOutput()
         o.convert(oeb, oIO, opts, log)
         self.SendToKindle(username, to, book.title, booktype, str(oIO.getvalue()), tz)
         rs = "%s(%s).%s Sent!"%(book.title, local_time(tz=tz), booktype)
         log.info(rs)
         return rs
     else:
         self.deliverlog(username, to, book.title, 0, status='fetch failed',tz=tz)
         rs = "[Url2Book]Fetch url failed."
         log.info(rs)
         return rs
示例#2
0
 def GET(self):
     username = web.input().get("u")
     url = web.input().get("url")
     subject = web.input().get("subject")
     to = web.input().get("to")
     language = web.input().get("lng")
     keepimage = bool(web.input().get("keepimage") == '1')
     booktype = web.input().get("type", "mobi")
     tz = int(web.input().get("tz", TIMEZONE))
     if not all((username,url,subject,to,language,booktype,tz)):
         return "Some parameter missing!<br />"
     
     book = BaseUrlBook()
     book.title = book.description = subject
     book.language = language
     book.keep_image = keepimage
     book.network_timeout = 60
     book.feeds = [(subject,url)]
     book.url_filters = [flt.url for flt in UrlFilter.all()]
     
     opts = oeb = None
     
     # 创建 OEB
     global log
     opts = getOpts()
     oeb = CreateOeb(log, None, opts)
     
     setMetaData(oeb, subject, language, local_time(tz=tz), pubtype='book:book:KindleEar')
     oeb.container = ServerContainer(log)
     
     # 对于html文件,变量名字自文档
     # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
     itemcnt = 0
     for sec_or_media, url, title, content, brief in book.Items(opts):
         if sec_or_media.startswith(r'image/'):
             id, href = oeb.manifest.generate(id='img', href=title)
             item = oeb.manifest.add(id, href, sec_or_media, data=content)
             itemcnt += 1
         else:
             id, href = oeb.manifest.generate(id='page', href='page.html')
             item = oeb.manifest.add(id, href, 'application/xhtml+xml', data=content)
             oeb.spine.add(item, False)
             oeb.toc.add(title, href)
             itemcnt += 1
         
     if itemcnt > 0:
         oIO = byteStringIO()
         o = EPUBOutput() if booktype == "epub" else MOBIOutput()
         o.convert(oeb, oIO, opts, log)
         self.SendToKindle(username, to, book.title, booktype, str(oIO.getvalue()), tz)
         rs = "%s(%s).%s Sent!"%(book.title, local_time(tz=tz), booktype)
         log.info(rs)
         return rs
     else:
         self.deliverlog(username, to, book.title, 0, status='fetch failed',tz=tz)
         rs = "[Url2Book]Fetch url failed."
         log.info(rs)
         return rs
示例#3
0
 def SaveToEvernoteWiz(self, user, action, orgUrl):
     if action == 'evernote' and (not user.evernote or not user.evernote_mail):
         main.log.warn('No have evernote mail yet.')
         return "No have evernote mail yet."
     elif action == 'wiz' and (not user.wiz or not user.wiz_mail):
         main.log.warn('No have wiz mail yet.')
         return "No have wiz mail yet."
         
     book = BaseUrlBook()
     book.title = book.description = action
     book.language = user.ownfeeds.language
     book.keep_image = user.ownfeeds.keep_image
     book.network_timeout = 60
     book.feeds = [(action, orgUrl)]
     book.url_filters = [flt.url for flt in user.urlfilter]
     
     attachments = [] #(filename, attachment),]
     html = ''
     title = action
     
     # 对于html文件,变量名字自文档
     # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
     for sec_or_media, url, title, content, brief, thumbnail in book.Items():
         if sec_or_media.startswith(r'image/'):
             if self.SHARE_IMAGE_EMBEDDED:
                 attachments.append(mail.Attachment(title, content, content_id='<%s>' % title))
             else:
                 attachments.append((title,content))
         else:
             soup = BeautifulSoup(content, 'lxml')
             
             #插入源链接
             p = soup.new_tag('p', style='font-size:80%;color:grey;')
             a = soup.new_tag('a', href=url)
             a.string = url
             p.string = 'origin : '
             p.append(a)
             soup.html.body.insert(0,p)
             
             if self.SHARE_IMAGE_EMBEDDED:
                 #内嵌图片标识
                 for img in soup.find_all('img', attrs={'src':True}):
                     img['src'] = 'cid:' + img['src']
             else:
                 #标注图片位置
                 for img in soup.find_all('img', attrs={'src':True}):
                     p = soup.new_tag('p')
                     p.string = 'Image : ' + img['src']
                     img.insert_after(p)
                 
             try:
                 title = unicode(soup.html.head.title.string)
             except:
                 pass
             
             html = unicode(soup)
             
     to = user.wiz_mail if action == 'wiz' else user.evernote_mail
     if (';' in to) or (',' in to):
         to = to.replace(',', ';').replace(' ', '').split(';')
     
     if html:
         self.SendHtmlMail(user.name, to, title, html.encode('utf-8'), attachments, user.timezone)
         info = _("'%(title)s'<br/><br/>Saved to %(act)s [%(email)s] success.") % ({'title':title,'act':action,'email':hide_email(to)})
         info += '<br/><p style="text-align:right;color:silver;">by KindleEar </p>'
         main.log.info(info)
         web.header('Content-type', "text/html; charset=utf-8")
         info = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
             <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>""" % (title, info)
         return info.encode('utf-8')
     else:
         self.deliverlog(user.name, str(to), title, 0, status='fetch failed', tz=user.timezone)
         main.log.info("[Share]Fetch url failed.")
         return "[Share]Fetch url failed."
示例#4
0
    def GET(self):
        username = web.input().get("u")
        urls = web.input().get("urls")
        subject = web.input().get("subject")
        to = web.input().get("to")
        language = web.input().get("lng")
        keepimage = bool(web.input().get("keepimage") == '1')
        booktype = web.input().get("type", "mobi")
        tz = int(web.input().get("tz", TIMEZONE))
        if not all((username, urls, subject, to, language, booktype, tz)):
            return "Some parameter missing!<br />"

        #global log

        if booktype == 'Download':  #直接下载电子书并推送
            from lib.filedownload import Download
            for url in urls.split('|'):
                dlinfo, filename, content = Download(url)
                #如果标题已经给定了文件名,则使用标题文件名
                if '.' in subject and (1 < len(subject.split('.')[-1]) < 5):
                    filename = subject

                if content:
                    self.SendToKindle(username, to, filename, '', content, tz)
                else:
                    if not dlinfo:
                        dlinfo = 'download failed'
                    self.deliverlog(username,
                                    to,
                                    filename,
                                    0,
                                    status=dlinfo,
                                    tz=tz)
                main.log.info("%s Sent!" % filename)
            return "%s Sent!" % filename

        user = KeUser.all().filter("name = ", username).get()
        if not user or not user.kindle_email:
            return "User not exist!<br />"

        book = BaseUrlBook()
        book.title = book.description = subject
        book.language = language
        book.keep_image = keepimage
        book.network_timeout = 60
        book.feeds = [(subject, url) for url in urls.split('|')]
        book.url_filters = [flt.url for flt in user.urlfilter]

        opts = oeb = None

        # 创建 OEB
        opts = getOpts(user.device)
        oeb = CreateOeb(main.log, None, opts)
        oeb.container = ServerContainer(main.log)

        if len(book.feeds) > 1:
            setMetaData(oeb, subject, language, local_time(tz=tz))
            id, href = oeb.manifest.generate('masthead', DEFAULT_MASTHEAD)
            oeb.manifest.add(id, href, MimeFromFilename(DEFAULT_MASTHEAD))
            oeb.guide.add('masthead', 'Masthead Image', href)
        else:
            setMetaData(oeb,
                        subject,
                        language,
                        local_time(tz=tz),
                        pubtype='book:book:KindleEar')

        id, href = oeb.manifest.generate('cover', DEFAULT_COVER)
        item = oeb.manifest.add(id, href, MimeFromFilename(DEFAULT_COVER))
        oeb.guide.add('cover', 'Cover', href)
        oeb.metadata.add('cover', id)

        # 对于html文件,变量名字自文档
        # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
        itemcnt, hasimage = 0, False
        sections = {subject: []}
        toc_thumbnails = {}  #map img-url -> manifest-href
        for sec_or_media, url, title, content, brief, thumbnail in book.Items(
                opts, user):
            if sec_or_media.startswith(r'image/'):
                id, href = oeb.manifest.generate(id='img', href=title)
                item = oeb.manifest.add(id, href, sec_or_media, data=content)
                if thumbnail:
                    toc_thumbnails[url] = href
                itemcnt += 1
                hasimage = True
            else:
                if len(book.feeds) > 1:
                    sections[subject].append(
                        (title, brief, thumbnail, content))
                else:
                    id, href = oeb.manifest.generate(id='page',
                                                     href='page.html')
                    item = oeb.manifest.add(id,
                                            href,
                                            'application/xhtml+xml',
                                            data=content)
                    oeb.spine.add(item, False)
                    oeb.toc.add(title, href)
                itemcnt += 1

        if itemcnt > 0:
            if len(book.feeds) > 1:
                InsertToc(oeb, sections, toc_thumbnails)
            elif not hasimage:  #单文章没有图片则去掉封面
                href = oeb.guide['cover'].href
                oeb.guide.remove('cover')
                item = oeb.manifest.hrefs[href]
                oeb.manifest.remove(item)
                oeb.metadata.clear('cover')

            oIO = byteStringIO()
            o = EPUBOutput() if booktype == "epub" else MOBIOutput()
            o.convert(oeb, oIO, opts, main.log)
            self.SendToKindle(username, to, book.title, booktype,
                              str(oIO.getvalue()), tz)
            rs = "%s(%s).%s Sent!" % (book.title, local_time(tz=tz), booktype)
            main.log.info(rs)
            return rs
        else:
            self.deliverlog(username,
                            to,
                            book.title,
                            0,
                            status='fetch failed',
                            tz=tz)
            rs = "[Url2Book]Fetch url failed."
            main.log.info(rs)
            return rs
示例#5
0
    def SaveToEvernoteWiz(self, user, action, orgUrl):
        if action == 'evernote' and (not user.evernote
                                     or not user.evernote_mail):
            main.log.warn('No have evernote mail yet.')
            return "No have evernote mail yet."
        elif action == 'wiz' and (not user.wiz or not user.wiz_mail):
            main.log.warn('No have wiz mail yet.')
            return "No have wiz mail yet."

        book = BaseUrlBook(user=user)
        book.title = book.description = action
        book.language = user.ownfeeds.language
        book.keep_image = user.ownfeeds.keep_image
        book.network_timeout = 60
        book.feeds = [(action, orgUrl)]
        book.url_filters = [flt.url for flt in user.urlfilter]

        attachments = []  #(filename, attachment),]
        html = ''
        title = action

        # 对于html文件,变量名字自文档
        # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
        for sec_or_media, url, title, content, brief, thumbnail in book.Items(
        ):
            if sec_or_media.startswith(r'image/'):
                if self.SHARE_IMAGE_EMBEDDED:
                    attachments.append(
                        mail.Attachment(title,
                                        content,
                                        content_id='<%s>' % title))
                else:
                    attachments.append((title, content))
            else:
                soup = BeautifulSoup(content, 'lxml')

                #插入源链接
                p = soup.new_tag('p', style='font-size:80%;color:grey;')
                a = soup.new_tag('a', href=url)
                a.string = url
                p.string = 'origin : '
                p.append(a)
                soup.html.body.insert(0, p)

                if self.SHARE_IMAGE_EMBEDDED:
                    #内嵌图片标识
                    for img in soup.find_all('img', attrs={'src': True}):
                        img['src'] = 'cid:' + img['src']
                else:
                    #标注图片位置
                    for img in soup.find_all('img', attrs={'src': True}):
                        p = soup.new_tag('p')
                        p.string = 'Image : ' + img['src']
                        img.insert_after(p)

                try:
                    title = unicode(soup.html.head.title.string)
                except:
                    pass

                html = unicode(soup)

        to = user.wiz_mail if action == 'wiz' else user.evernote_mail
        if (';' in to) or (',' in to):
            to = to.replace(',', ';').replace(' ', '').split(';')

        if html:
            self.SendHtmlMail(user.name, to, title, html.encode('utf-8'),
                              attachments, user.timezone)
            info = _(
                "'%(title)s'<br/><br/>Saved to %(act)s [%(email)s] success."
            ) % ({
                'title': title,
                'act': action,
                'email': hide_email(to)
            })
            info += '<br/><p style="text-align:right;color:silver;">by KindleEar </p>'
            main.log.info(info)
            web.header('Content-type', "text/html; charset=utf-8")
            info = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>""" % (
                title, info)
            return info.encode('utf-8')
        else:
            self.deliverlog(user.name,
                            str(to),
                            title,
                            0,
                            status='fetch failed',
                            tz=user.timezone)
            main.log.info("[Share]Fetch url failed.")
            return "[Share]Fetch url failed."
示例#6
0
    def GET(self):
        import urlparse, urllib
        action = web.input().get('act')
        username = web.input().get("u")
        url = web.input().get("url")
        if not username or not url or not action:
            return "Some parameter is missing or wrong!<br />"

        user = KeUser.all().filter("name = ", username).get()
        if not user or not user.kindle_email:
            return "User not exist!<br />"

        #global log

        url = urllib.unquote(url)

        #因为知乎好文章比较多,特殊处理一下知乎
        #if urlparse.urlsplit(url)[1].endswith('zhihu.com'):
        #    url = SHARE_FUCK_GFW_SRV % urllib.quote(url.encode('utf-8'))

        if action in ('evernote', 'wiz'):  #保存至evernote/wiz
            if action == 'evernote' and (not user.evernote
                                         or not user.evernote_mail):
                main.log.warn('No have evernote mail yet.')
                return "No have evernote mail yet."
            elif action == 'wiz' and (not user.wiz or not user.wiz_mail):
                main.log.warn('No have wiz mail yet.')
                return "No have wiz mail yet."

            book = BaseUrlBook()
            book.title = book.description = action
            book.language = user.ownfeeds.language
            book.keep_image = user.ownfeeds.keep_image
            book.network_timeout = 60
            book.feeds = [(action, url)]
            book.url_filters = [flt.url for flt in user.urlfilter]

            attachments = []  #(filename, attachment),]
            html = ''
            title = action

            # 对于html文件,变量名字自文档
            # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
            for sec_or_media, url, title, content, brief, thumbnail in book.Items(
            ):
                if sec_or_media.startswith(r'image/'):
                    if self.SHARE_IMAGE_EMBEDDED:
                        attachments.append(
                            mail.Attachment(title,
                                            content,
                                            content_id='<%s>' % title))
                    else:
                        attachments.append((title, content))
                else:
                    soup = BeautifulSoup(content, 'lxml')

                    #插入源链接
                    p = soup.new_tag('p', style='font-size:80%;color:grey;')
                    a = soup.new_tag('a', href=url)
                    a.string = url
                    p.string = 'origin : '
                    p.append(a)
                    soup.html.body.insert(0, p)

                    if self.SHARE_IMAGE_EMBEDDED:
                        #内嵌图片标识
                        for img in soup.find_all('img', attrs={'src': True}):
                            img['src'] = 'cid:' + img['src']
                    else:
                        #标注图片位置
                        for img in soup.find_all('img', attrs={'src': True}):
                            p = soup.new_tag('p')
                            p.string = 'Image : ' + img['src']
                            img.insert_after(p)

                    try:
                        title = unicode(soup.html.head.title.string)
                    except:
                        pass

                    html = unicode(soup)

            to = user.wiz_mail if action == 'wiz' else user.evernote_mail
            if html:
                self.SendHtmlMail(username, to, title, html, attachments,
                                  user.timezone)
                info = u'"%s" saved to %s (%s).' % (title, action,
                                                    hide_email(to))
                main.log.info(info)
                web.header('Content-type', "text/html; charset=utf-8")
                info = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                    <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>""" % (
                    title, info)
                return info.encode('utf-8')
            else:
                self.deliverlog(username,
                                to,
                                title,
                                0,
                                status='fetch failed',
                                tz=user.timezone)
                main.log.info("[Share]Fetch url failed.")
                return "[Share]Fetch url failed."
        else:
            return "Unknown parameter 'action'!"
示例#7
0
文件: main.py 项目: ddt12/KindleEar
 def GET(self):
     action = web.input().get('act')
     username = web.input().get("u")
     url = web.input().get("url")
     if not username or not url or not action:
         return "Some parameter is missing or wrong!<br />"
     
     user = KeUser.all().filter("name = ", username).get()
     if not user or not user.kindle_email:
         return "User not exist!<br />"
     
     global log
     
     if action in ('evernote','wiz'): #保存至evernote/wiz
         if action=='evernote' and (not user.evernote or not user.evernote_mail):
             log.warn('No have evernote mail yet.')
             return "No have evernote mail yet."
         elif action=='wiz' and (not user.wiz or not user.wiz_mail):
             log.warn('No have wiz mail yet.')
             return "No have wiz mail yet."
             
         book = BaseUrlBook()
         book.title = book.description = action
         book.language = user.ownfeeds.language
         book.keep_image = user.ownfeeds.keep_image
         book.network_timeout = 60
         book.feeds = [(action,url)]
         book.url_filters = [flt.url for flt in user.urlfilter]
         
         attachments = [] #(filename, attachment),]
         html = ''
         title = action
         
         # 对于html文件,变量名字自文档
         # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
         for sec_or_media, url, title, content, brief in book.Items():
             if sec_or_media.startswith(r'image/'):
                 attachments.append((title,content))
             else:
                 soup = BeautifulSoup(content, 'lxml')
                 
                 #插入源链接
                 p = soup.new_tag('p', style='font-size:80%;color:grey;')
                 a = soup.new_tag('a', href=url)
                 a.string = url
                 p.string = 'origin : '
                 p.append(a)
                 soup.html.body.insert(0,p)
                 
                 #标注图片位置
                 for img in soup.find_all('img', attrs={'src':True}):
                     p = soup.new_tag('p')
                     p.string = 'Image : ' + img['src']
                     img.insert_after(p)
                 
                 try:
                     title = unicode(soup.html.head.title.string)
                 except:
                     pass
                 
                 html = unicode(soup)
                 
         to = user.wiz_mail if action=='wiz' else user.evernote_mail
         if html:
             self.SendHtmlMail(username,to,title,html,attachments,user.timezone)
             info = "'%s' saved to %s (%s)." % (title,action,hide_email(to))
             log.info(info)
             web.header('Content-type', "text/html; charset=utf-8")
             info = """<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                 <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>""" % (title, info)
             return info.encode('utf-8')
         else:
             self.deliverlog(username,to,title,0,status='fetch failed',tz=user.timezone)
             log.info("[Share]Fetch url failed.")
             return "[Share]Fetch url failed."
     else:
         return "Unknown parameter 'action'!"
示例#8
0
    def GET(self):
        import urlparse, urllib

        action = web.input().get("act")
        username = web.input().get("u")
        url = web.input().get("url")
        if not username or not url or not action:
            return "Some parameter is missing or wrong!<br />"

        user = KeUser.all().filter("name = ", username).get()
        if not user or not user.kindle_email:
            return "User not exist!<br />"

        # global log

        url = urllib.unquote(url)

        # 因为知乎好文章比较多,特殊处理一下知乎
        # if urlparse.urlsplit(url)[1].endswith('zhihu.com'):
        #    url = SHARE_FUCK_GFW_SRV % urllib.quote(url.encode('utf-8'))

        if action in ("evernote", "wiz"):  # 保存至evernote/wiz
            if action == "evernote" and (not user.evernote or not user.evernote_mail):
                main.log.warn("No have evernote mail yet.")
                return "No have evernote mail yet."
            elif action == "wiz" and (not user.wiz or not user.wiz_mail):
                main.log.warn("No have wiz mail yet.")
                return "No have wiz mail yet."

            book = BaseUrlBook()
            book.title = book.description = action
            book.language = user.ownfeeds.language
            book.keep_image = user.ownfeeds.keep_image
            book.network_timeout = 60
            book.feeds = [(action, url)]
            book.url_filters = [flt.url for flt in user.urlfilter]

            attachments = []  # (filename, attachment),]
            html = ""
            title = action

            # 对于html文件,变量名字自文档
            # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
            for sec_or_media, url, title, content, brief, thumbnail in book.Items():
                if sec_or_media.startswith(r"image/"):
                    if self.SHARE_IMAGE_EMBEDDED:
                        attachments.append(mail.Attachment(title, content, content_id="<%s>" % title))
                    else:
                        attachments.append((title, content))
                else:
                    soup = BeautifulSoup(content, "lxml")

                    # 插入源链接
                    p = soup.new_tag("p", style="font-size:80%;color:grey;")
                    a = soup.new_tag("a", href=url)
                    a.string = url
                    p.string = "origin : "
                    p.append(a)
                    soup.html.body.insert(0, p)

                    if self.SHARE_IMAGE_EMBEDDED:
                        # 内嵌图片标识
                        for img in soup.find_all("img", attrs={"src": True}):
                            img["src"] = "cid:" + img["src"]
                    else:
                        # 标注图片位置
                        for img in soup.find_all("img", attrs={"src": True}):
                            p = soup.new_tag("p")
                            p.string = "Image : " + img["src"]
                            img.insert_after(p)

                    try:
                        title = unicode(soup.html.head.title.string)
                    except:
                        pass

                    html = unicode(soup)

            to = user.wiz_mail if action == "wiz" else user.evernote_mail
            if html:
                self.SendHtmlMail(username, to, title, html, attachments, user.timezone)
                info = u'"%s" saved to %s (%s).' % (title, action, hide_email(to))
                main.log.info(info)
                web.header("Content-type", "text/html; charset=utf-8")
                info = u"""<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                    <title>%s</title></head><body><p style="text-align:center;font-size:1.5em;">%s</p></body></html>""" % (
                    title,
                    info,
                )
                return info.encode("utf-8")
            else:
                self.deliverlog(username, to, title, 0, status="fetch failed", tz=user.timezone)
                main.log.info("[Share]Fetch url failed.")
                return "[Share]Fetch url failed."
        else:
            return "Unknown parameter 'action'!"
示例#9
0
 def GET(self):
     username = web.input().get("u")
     urls = web.input().get("urls")
     subject = web.input().get("subject")
     to = web.input().get("to")
     language = web.input().get("lng")
     keepimage = bool(web.input().get("keepimage") == '1')
     booktype = web.input().get("type", "mobi")
     tz = int(web.input().get("tz", TIMEZONE))
     if not all((username,urls,subject,to,language,booktype,tz)):
         return "Some parameter missing!<br />"
     
     #global log
     
     if booktype == 'Download': #直接下载电子书并推送
         from lib.filedownload import Download
         for url in urls.split('|'):
             dlinfo, filename, content = Download(url)
             #如果标题已经给定了文件名,则使用标题文件名
             if '.' in subject and (1 < len(subject.split('.')[-1]) < 5):
                 filename = subject
                 
             if content:
                 self.SendToKindle(username, to, filename, '', content, tz)
             else:
                 if not dlinfo:
                     dlinfo = 'download failed'
                 self.deliverlog(username, to, filename, 0, status=dlinfo,tz=tz)
             main.log.info("%s Sent!" % filename)
         return "%s Sent!" % filename
         
     user = KeUser.all().filter("name = ", username).get()
     if not user or not user.kindle_email:
         return "User not exist!<br />"
         
     book = BaseUrlBook()
     book.title = book.description = subject
     book.language = language
     book.keep_image = keepimage
     book.network_timeout = 60
     book.feeds = [(subject,url) for url in urls.split('|')]
     book.url_filters = [flt.url for flt in user.urlfilter]
     
     opts = oeb = None
     
     # 创建 OEB
     opts = getOpts(user.device)
     oeb = CreateOeb(main.log, None, opts)
     oeb.container = ServerContainer(main.log)
     
     if len(book.feeds) > 1:
         setMetaData(oeb, subject, language, local_time(tz=tz))
         id, href = oeb.manifest.generate('masthead', DEFAULT_MASTHEAD)
         oeb.manifest.add(id, href, MimeFromFilename(DEFAULT_MASTHEAD))
         oeb.guide.add('masthead', 'Masthead Image', href)
     else:
         setMetaData(oeb, subject, language, local_time(tz=tz), pubtype='book:book:KindleEar')
     
     id, href = oeb.manifest.generate('cover', DEFAULT_COVER)
     item = oeb.manifest.add(id, href, MimeFromFilename(DEFAULT_COVER))
     oeb.guide.add('cover', 'Cover', href)
     oeb.metadata.add('cover', id)
     
     # 对于html文件,变量名字自文档
     # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
     itemcnt,hasimage = 0,False
     sections = {subject:[]}
     toc_thumbnails = {} #map img-url -> manifest-href
     for sec_or_media, url, title, content, brief, thumbnail in book.Items(opts,user):
         if sec_or_media.startswith(r'image/'):
             id, href = oeb.manifest.generate(id='img', href=title)
             item = oeb.manifest.add(id, href, sec_or_media, data=content)
             if thumbnail:
                 toc_thumbnails[url] = href
             itemcnt += 1
             hasimage = True
         else:
             if len(book.feeds) > 1:
                 sections[subject].append((title,brief,thumbnail,content))
             else:
                 id, href = oeb.manifest.generate(id='page', href='page.html')
                 item = oeb.manifest.add(id, href, 'application/xhtml+xml', data=content)
                 oeb.spine.add(item, False)
                 oeb.toc.add(title, href)
             itemcnt += 1
         
     if itemcnt > 0:
         if len(book.feeds) > 1:
             InsertToc(oeb, sections, toc_thumbnails)
         elif not hasimage: #单文章没有图片则去掉封面
             href = oeb.guide['cover'].href
             oeb.guide.remove('cover')
             item = oeb.manifest.hrefs[href]
             oeb.manifest.remove(item)
             oeb.metadata.clear('cover')
             
         oIO = byteStringIO()
         o = EPUBOutput() if booktype == "epub" else MOBIOutput()
         o.convert(oeb, oIO, opts, main.log)
         self.SendToKindle(username, to, book.title, booktype, str(oIO.getvalue()), tz)
         rs = "%s(%s).%s Sent!"%(book.title, local_time(tz=tz), booktype)
         main.log.info(rs)
         return rs
     else:
         self.deliverlog(username, to, book.title, 0, status='fetch failed',tz=tz)
         rs = "[Url2Book]Fetch url failed."
         main.log.info(rs)
         return rs
示例#10
0
    def GET(self):
        username = web.input().get("u")
        urls = web.input().get("urls")
        subject = web.input().get("subject")
        to = web.input().get("to")
        language = web.input().get("lng")
        keepimage = bool(web.input().get("keepimage") == '1')
        booktype = web.input().get("type", "mobi")
        tz = int(web.input().get("tz", TIMEZONE))
        if not all((username, urls, subject, to, language, booktype, tz)):
            return "Some parameter missing!<br />"

        if (';' in to) or (',' in to):
            to = to.replace(',', ';').replace(' ', '').split(';')
            to = list(filter(lambda x: x.find('@', 1,
                                              len(x) - 1) > 0,
                             to))  #最简单的判断是否是EMAIL

        if type(urls) is unicode:
            urls = urls.encode('utf-8')

        urls = zlib.decompress(base64.urlsafe_b64decode(urls))

        if booktype == 'Download':  #直接下载电子书并推送
            from lib.filedownload import Download
            for url in urls.split('|'):
                dlinfo, filename, content = Download(url)
                #如果标题已经给定了文件名,则使用标题文件名
                if '.' in subject and (1 < len(subject.split('.')[-1]) < 5):
                    filename = subject

                if content:
                    self.SendToKindle(username, to, filename, '', content, tz)
                else:
                    if not dlinfo:
                        dlinfo = 'download failed'
                    self.deliverlog(username,
                                    str(to),
                                    filename,
                                    0,
                                    status=dlinfo,
                                    tz=tz)
                main.log.info("%s Sent!" % filename)
            return "%s Sent!" % filename
        elif booktype == 'Debug':  #调试目的,将链接直接下载,发送到管理员邮箱
            from books.base import debug_fetch
            #如果标题已经给定了文件名,则使用标题文件名,否则为默认文件名(page.html)
            filename = None
            if '.' in subject and (1 < len(subject.split('.')[-1]) < 5):
                filename = subject

            for url in urls.split('|'):
                debug_fetch(url, filename)
            main.log.info('[DEBUG] debug file sent!')
            return 'Debug file sent!'

        user = KeUser.all().filter("name = ", username).get()
        if not user or not user.kindle_email:
            return "User not exist!<br />"

        opts = getOpts(user.device)

        book = BaseUrlBook(opts=opts, user=user)
        book.title = book.description = subject
        book.language = language
        book.keep_image = keepimage
        book.network_timeout = 60
        book.feeds = [(subject, url) for url in urls.split('|')]
        book.url_filters = [flt.url for flt in user.urlfilter]

        # 创建 OEB
        oeb = CreateOeb(main.log, None, opts)
        oeb.container = ServerContainer(main.log)

        if len(book.feeds) > 1:
            setMetaData(oeb, subject, language, local_time(tz=tz))
            id_, href = oeb.manifest.generate('masthead', DEFAULT_MASTHEAD)
            oeb.manifest.add(id_, href, MimeFromFilename(DEFAULT_MASTHEAD))
            oeb.guide.add('masthead', 'Masthead Image', href)
        else:
            setMetaData(oeb,
                        subject,
                        language,
                        local_time(tz=tz),
                        pubtype='book:book:KindleEar')

        # id, href = oeb.manifest.generate('cover', DEFAULT_COVER)
        # item = oeb.manifest.add(id, href, MimeFromFilename(DEFAULT_COVER))
        # oeb.guide.add('cover', 'Cover', href)
        # oeb.metadata.add('cover', id)

        # 对于html文件,变量名字自文档
        # 对于图片文件,section为图片mime,url为原始链接,title为文件名,content为二进制内容
        itemcnt, hasimage = 0, False
        sections = {subject: []}
        toc_thumbnails = {}  #map img-url -> manifest-href
        for sec_or_media, url, title, content, brief, thumbnail in book.Items(
        ):
            if sec_or_media.startswith(r'image/'):
                id_, href = oeb.manifest.generate(id='img', href=title)
                item = oeb.manifest.add(id_, href, sec_or_media, data=content)
                if thumbnail:
                    toc_thumbnails[url] = href
                itemcnt += 1
                hasimage = True
            else:
                if len(book.feeds) > 1:
                    sections[subject].append(
                        (title, brief, thumbnail, content))
                else:
                    id_, href = oeb.manifest.generate(id='page',
                                                      href='page.html')
                    item = oeb.manifest.add(id_,
                                            href,
                                            'application/xhtml+xml',
                                            data=content)
                    oeb.spine.add(item, False)
                    oeb.toc.add(title, href)

                itemcnt += 1

        if itemcnt > 0:
            if len(book.feeds) > 1:
                InsertToc(oeb, sections, toc_thumbnails, GENERATE_HTML_TOC,
                          GENERATE_TOC_THUMBNAIL)
                # elif not hasimage: #单文章没有图片则去掉封面
                # href = oeb.guide['cover'].href
                # oeb.guide.remove('cover')
                # item = oeb.manifest.hrefs[href]
                # oeb.manifest.remove(item)
                # oeb.metadata.clear('cover')

            oIO = byteStringIO()
            o = EPUBOutput() if booktype == "epub" else MOBIOutput()
            o.convert(oeb, oIO, opts, main.log)
            self.SendToKindle(username, to, book.title, booktype,
                              str(oIO.getvalue()), tz)
            rs = "%s(%s).%s Sent!" % (book.title, local_time(tz=tz), booktype)
            main.log.info(rs)
            return rs
        else:
            self.deliverlog(username,
                            str(to),
                            book.title,
                            0,
                            status='fetch failed',
                            tz=tz)
            rs = "[Url2Book]Fetch url failed."
            main.log.info(rs)
            return rs