Skip to content

Commit

Permalink
porting to python3
Browse files Browse the repository at this point in the history
  • Loading branch information
cdhigh committed Feb 15, 2024
1 parent b4b9467 commit 5a499bf
Show file tree
Hide file tree
Showing 36 changed files with 2,750 additions and 2,749 deletions.
2 changes: 1 addition & 1 deletion app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ basic_scaling:
# min_idle_instances: 0

app_engine_apis: true
entrypoint: gunicorn -b :$PORT main:app
entrypoint: gunicorn -b :$PORT -w 2 main:app

inbound_services:
- mail
Expand Down
12 changes: 3 additions & 9 deletions application/back_end/db_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,16 +95,10 @@ def get_cover_data(self):
return data

#获取用户自定义的CSS
#css为Recipe预定义的CSS
#返回两个CSS合并后的字符串
def get_extra_css(self, css=''):
def get_extra_css(self):
dbItem = UserBlob.get_or_none((UserBlob.user == self.name) & (UserBlob.name == 'css'))
if dbItem:
extra_css = dbItem.data.decode('utf-8')
return (css + '\n\n' + extra_css) if css else extra_css
else:
return css

return dbItem.data.decode('utf-8') if dbItem else ''

#用户的一些二进制内容,比如封面之类的
class UserBlob(MyBaseModel):
name = CharField()
Expand Down
16 changes: 10 additions & 6 deletions application/back_end/send_mail_adpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,22 @@

#发送邮件
#title: 邮件标题
#attachment: 附件二进制内容
#attachment: 附件二进制内容,或元祖 (filename, content)
#fileWithTime: 发送的附件文件名是否附带当前时间
def send_to_kindle(user, title, attachment, fileWithTime=True):
lcTime = local_time('%Y-%m-%d_%H-%M', user.timezone)
subject = f"KindleEar {lcTime}"
lcTime = "({})".format(lcTime) if fileWithTime else ""
ext = ".{}".format(user.book_type) if user.book_type else ""
fileName = f"{title}{lcTime}{ext}"
body = "Deliver from KindleEar"
attachments = [(fileName, attachment)]

if not isinstance(attachment, tuple):
lcTime = "({})".format(lcTime) if fileWithTime else ""
fileName = f"{title}{lcTime}.{user.book_type}"
attachment = (fileName, attachment)

if not isinstance(attachment, list):
attachments = [attachment]

status = 'ok'
body = "Deliver from KindleEar"
try:
send_mail(user, user.kindle_email, subject, body, attachments)
except Exception as e:
Expand Down
3 changes: 2 additions & 1 deletion application/lib/build_ebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ def urls_to_book(urls: list, title: str, user, options: dict=None, output_fmt: s
return None

#合并自定义css
ro.extra_css = user.get_extra_css(ro.extra_css)
userCss = user.get_extra_css()
ro.extra_css = f'{ro.extra_css}\n\n{userCss}' if ro.extra_css else userCss

return recipes_to_ebook(ro, user, options, output_fmt)

Expand Down
5 changes: 3 additions & 2 deletions application/lib/calibre/customize/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,9 @@ class InputFormatPlugin(Plugin):
'set this option will override any encoding declared by the '
'document itself. Particularly useful for documents that '
'do not declare an encoding or that have erroneous '
'encoding declarations.')
)}
'encoding declarations.')),
OptionRecommendation(name='user', recommended_value=None,
help='Keuser instance.'),}

#: Options to customize the behavior of this plugin. Every option must be an
#: instance of :class:`OptionRecommendation`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ def convert(self, input_, opts, file_ext, log, output_dir, fs):

#manifest 资源列表
manifest = ['/index.html']
for filename, content in input_.get('imgs', []):
filename = os.path.join(fs.path, filename)
for fileName, content in input_.get('imgs', []):
fileName = os.path.join(fs.path, fileName)
fs.write(fileName, content)
manifest.append(filename)
manifest.append(fileName)
opf.create_manifest_from_files_in(manifest)
ncx_id = opf.manifest.add_item(os.path.join(fs.path, 'index.ncx'), mime_type="application/x-dtbncx+xml")
opf.manifest.item(ncx_id).id = 'ncx'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ class RecipeInput(InputFormatPlugin):
help=_('Do not download latest version of builtin recipes from the calibre server')),
OptionRecommendation(name='lrf', recommended_value=False,
help='Optimize fetching for subsequent conversion to LRF.'),
OptionRecommendation(name='user', recommended_value=None,
help='Keuser instance.'),
}

#执行转换完成后返回生成的 opf 文件路径,只是路径,不包含文件名
Expand Down
9 changes: 4 additions & 5 deletions application/lib/calibre/ebooks/conversion/plumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ def run(self):
fs = FsDictStub(tdir)
else:
tdir = '/'
fs = FsDictStub(None)
fs = FsDictStub()

#调用calibre.customize.conversion.InputFormatPlugin.__call__(),然后调用输入插件的convert()在目标目录生成一大堆文件,包含opf
#__call__()返回传入的 fs 实例,其属性 opfname 保存了opf文件的路径名
Expand Down Expand Up @@ -551,16 +551,15 @@ def run(self):
self.log.info('Processed HTML written to:{}'.format(out_dir))

self.log.info('Creating %s...'%self.output_plugin.name)

#创建输出临时文件缓存
if system_temp_dir:
prefix = self.output_plugin.commit_name or 'output_'
tmpdir = PersistentTemporaryDirectory(prefix=prefix, dir=system_temp_dir)
fs_out = FsDictStub(tmpdir)
else:
fs_out = FsDictStub(None)
fs_out = fs

fs_out = FsDictStub()

#这才是启动输出转换,生成电子书
with self.output_plugin:
self.output_plugin.convert(self.oeb, self.output, self.input_plugin, self.opts, self.log, fs_out)
Expand Down
10 changes: 5 additions & 5 deletions application/lib/filedownload.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@
"""
from collections import namedtuple
from urllib.parse import urlparse
from lib.urlopener import UrlOpener
from urlopener import UrlOpener

DownloadedFileTuple = namedtuple("DownloadedFileTuple", "status fileName content")

#FileDownload工具函数,简化文件下载工作
#返回一个命名元祖 DownloadedFileTuple
def Download(url):
fileName = lambda url: urlparse(url).path.split('/')[-1]
fileName = urlparse(url).path.split('/')[-1]

opener = UrlOpener()
resp = opener.open(url)
content = resp.content

if resp.status_code == 413:
return DownloadedFileTuple('too large', fileName, '')
return DownloadedFileTuple('too large', fileName, b'')
elif resp.status_code not in (200, 206):
return DownloadedFileTuple('download failed', fileName, '')
return DownloadedFileTuple('download failed', fileName, b'')
elif not content:
return DownloadedFileTuple('not resuming', fileName, '')
return DownloadedFileTuple('not resuming', fileName, b'')
else:
return DownloadedFileTuple('', fileName, content)

4 changes: 2 additions & 2 deletions application/lib/filesystem_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def delete(self, path: str):

#全部清除,释放内存
def clear(self):
self.dirs = None
self.dirs = set()
for key in list(self.keys()):
del self[key]

Expand Down Expand Up @@ -101,7 +101,7 @@ def _update_dirs(self):
#提供给OEB的文件读写桩,给外部提供一个统一的文件系统接口,内部根据情况使用模拟文件系统字典或调用系统函数
class FsDictStub(object):
#path: 如果path=str,则使用操作系统文件读写,否则使用path对应的FileSystemDict读写
def __init__(self, path, log=None, ignore_opf=False):
def __init__(self, path=None, log=None, ignore_opf=False):
if path:
assert(os.path.isabs(path))
self.path = path
Expand Down
11 changes: 5 additions & 6 deletions application/static/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ function PopulateMySubscribed() {
row_str.push(title);
}
if (separated) {
//row_str.push('<img alt="' + i18n.separated + '" src="static/separate.gif" border="0" />');
row_str.push('<sup> Sep</sup>');
}
row_str.push('</div><div class="summaryRow">');
Expand Down Expand Up @@ -517,16 +516,16 @@ function ShareRssToServer(id, title, category, lang) {
$.post("/library", {id: id, category: category, title: title, lang: lang, creator: window.location.hostname}, function (data) {
if (data.status == "ok") {
var idx = g_rss_categories.indexOf(category);
if (g_rss_categories && (category != "")) { //将刚才使用到的分类移动到开头
if (idx > 0){
g_rss_categories.splice(idx, 1);
if (g_rss_categories && (category != "")) {
if (idx > 0) {
g_rss_categories.splice(idx, 1); //将刚才使用到的分类移动到开头
}
if (idx != 0) {
g_rss_categories.unshift(category);
g_rss_categories.unshift(category); //添加一个新的类别
}
}
window.localStorage.setItem('rss_category', JSON.stringify(g_rss_categories));
window.localStorage.setItem('shared_rss', ''); //让分享库页面从服务器取新数据
window.localStorage.setItem('shared_rss', ''); //清除本地存储,让分享库页面从服务器取新数据
ShowSimpleModalDialog('<p>' + i18n.thankForShare + '</p>');
} else if (data.status == i18n.loginRequired) {
window.location.href = '/login';
Expand Down
4 changes: 2 additions & 2 deletions application/templates/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<div class="main">
<form class="pure-form pure-form-aligned" action="" method="POST" onsubmit="return false;">
<fieldset>
<legend><h3>{{_("Change Password")}}</h3></legend>
<legend><h3>{{_('Change Password')}}</h3></legend>
{% if chpwdtips -%}
<div class="notice-box">{{chpwdtips|safe}}</div>
{% endif -%}
Expand Down Expand Up @@ -84,7 +84,7 @@
<tr>
<th>{{_("No.")}}</th>
<th>{{_("Username")}}</th>
<th>{{_("Enable")}}</th>
<th>{{_("AutoSend")}}</th>
<th>{{_("Expiration")}}</th>
<th>{{_("Operation")}}</th>
</tr>
Expand Down
4 changes: 2 additions & 2 deletions application/templates/adv_uploadcover.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
<div id="preview" class="imgupBox">
<div class="imgFileUploade">
<div class="pure-control-group">
<label style="margin: 0px 20px">{{_("Apply Cover Image Order")}}</label>
<label style="margin: 0px 20px">{{_("Rule to pick cover images")}}</label>
<select class="pure-u-1 pure-u-sm-1-2" name="order" id="coverOrder">
<option value="random" {% if covers.get('order', 'random') == 'random' %}selected="selected"{% endif %}>{{_("Random")}}</option>
<option value="sequential" {% if covers.get('order') == 'sequential' %}selected="selected"{% endif %}>{{_("Sequential")}}</option>
<option value="weekday" {% if covers.get('order') == 'weekday' %}selected="selected"{% endif %}>{{_("Weekday")}}</option>
</select>
</div>
<hr style="width: 90%" />
Expand Down
6 changes: 2 additions & 4 deletions application/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

{% autoescape off %}
<script type="text/javascript">
//在所有脚本里面用到的字符串翻译都放在这里让pybabel可以简单提取,脚本里面使用键名引用
var i18n = {
delete: '{{_("Delete")|safe}}',
viewSrc: '{{_("View Source Code")|safe}}',
Expand All @@ -38,7 +37,6 @@
langInvalid: '{{_("Language code invalid")|safe}}',
thankForShare: '{{_("Thank you for sharing.")|safe}}',
close: '{{_("Close")|safe}}',
separated: '{{_("Separated")|safe}}',
unsubscribe: '{{_("Unsubscribe")|safe}}',
cannotSubsRecipe: '{{_("Cannot subscribe this recipe, Error:")|safe}}',
areYouSureUnsubscribe: '{{_("Are you sure to Unsubscribe ({0})?")|safe}}',
Expand All @@ -50,7 +48,7 @@
submit: '{{_("Submit")|safe}}',
recipeLoginTips: '{{_("If any field is left blank, the server will clear the saved login information.")|safe}}',
cannotSetSubsInfo: '{{_("Cannot set the subscription infomation, Error:")|safe}}',
chooseRecipeFile: '{{_("Choose a recipe file for upload")|safe}}',
chooseRecipeFile: '{{_("Choose a recipe file to upload")|safe}}',
congratulations: '{{_("Congratulations")|safe}}',
thanks: '{{_("Thanks")|safe}}',
recipeUploadedTips: '{{_("Your recipe has been uploaded, and it can be found in the Library section. If you dont see it, please make sure to switch to the correct language.")|safe}}',
Expand Down Expand Up @@ -88,7 +86,7 @@
addAccountOk: '{{_("Account added successfully.")|safe}}',
loginRequired: '{{_("login required")|safe}}',
uploadCoversOk: '{{_("Upload cover files successfully.")|safe}}',
imgSizeToLarge: '{{_("Total size of the files you selected exceeds 16MB. Please reduce the image resolution or upload in batches.")|safe}}',
imgSizeToLarge: '{{_("Total size of the files you selected exceeds 16MB. Please reduce the image resolution or upload in batches.")|safe}}'
};
</script>
{% block javascript_inhead %}
Expand Down
2 changes: 1 addition & 1 deletion application/templates/library.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
</div>
<div class="pure-u-1 pure-u-md-12-24">
<div class="pure-form pure-form-aligned">
<input type="text" id="search_text" onkeyup="DoSearchInShared()" class="pure-input-rounded pure-input-rounded width100" placeholder="Search" />
<input type="text" id="search_text" onkeyup="DoSearchInShared()" class="pure-input-rounded pure-input-rounded width100" placeholder="{{_('Search')}}" />
<p></p>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion application/templates/my.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
<div class="pure-u-2-5 pure-u-sm-1-4 pure-u-md-1-6">
<div>
<label style="white-space: nowrap;"><input type="checkbox" name="fulltext" id="isfulltext" />
Content embedded</label>
{{_("Content embedded")}}</label>
</div>
</div>
</div>
Expand Down
8 changes: 5 additions & 3 deletions application/templates/setting.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<div class="main">
{% if user.expires -%}
<div class="grey">
{{_("Your account will pause after")}} <strong id="expires">{{ user.expires.strftime("%Y-%m-%d") }}</strong> {{_(", Please login before expire.")}}
{{_("Your account will pause after {0}, please log in again before it expires.").format(user.expires.strftime("%Y-%m-%d")) }}<br />
<a href="/delaccount/{{user.name}}">{{_("Delete Account")}}</a>
</div>
{% endif -%}
Expand Down Expand Up @@ -214,8 +214,10 @@
<input type="text" name="sm_save_path" value="{{sm_srv.get('save_path', 'tests/debug_mail')}}" class="pure-u-1 pure-u-sm-1-2" />
</div>
</fieldset>

<p>{{_("Important: Please activate your kindle firstly, and goto")}}“<a href="https://www.amazon.com/hz/mycd/myx#/home/settings/payment" rel="external" target="_blank">{{_("Personal Document Settings")}}</a>”{{_("Page and add")}} <strong>{{ mailSender }}</strong> {{_("to 'Approved Personal Document E-mail List'.")}}
<p>
{% autoescape off -%}
{{_("Important: Please activate your kindle firstly, then goto %(personal)s Page and add %(sender)s to 'Approved Personal Document E-mail List'.", personal='<a href="https://www.amazon.com/hz/mycd/myx#/home/settings/payment" rel="external" target="_blank">' + _("Personal Document Settings") + '</a>', sender='<strong>' + mailSender + '</strong>')|safe}}
{% endautoescape -%}
</p>
<p style="text-align:center;">
<input type="submit" class="pure-button pure-button-primary pure-input-rounded" value="{{_('Save settings')}}" />
Expand Down
Binary file modified application/translations/tr_TR/LC_MESSAGES/messages.mo
Binary file not shown.
Loading

0 comments on commit 5a499bf

Please sign in to comment.