Skip to content

Commit

Permalink
can directly create cards on eow.alc.co.jp now
Browse files Browse the repository at this point in the history
  • Loading branch information
dayjaby committed Sep 8, 2016
1 parent b2e7a20 commit 0bfd356
Show file tree
Hide file tree
Showing 16 changed files with 132 additions and 36 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
*.pyc
*.swp
yomichan.zip
yomichan_dicts.zip
yomichan_dict_european.zip
Expand All @@ -8,4 +9,4 @@ yomi_base/languages/german/de-eng.txt
yomi_base/languages/spanish/es-eng.txt
*.db
*.u8
.idea
.idea
Binary file modified app.crx
Binary file not shown.
11 changes: 11 additions & 0 deletions app/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@
],
"run_at": "document_end",
"all_frames": false
},
{
"matches": [
"http://eow.alc.co.jp/*",
"https://eow.alc.co.jp/*"
],
"js": [
"scripts/eow.js"
],
"run_at": "document_end",
"all_frames": false
}
],
"content_security_policy": "script-src 'self'; object-src 'self'",
Expand Down
Binary file removed app/scripts/.contentscript.js.swp
Binary file not shown.
5 changes: 0 additions & 5 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
'use strict';


//$http.post('http://127.0.0.1:8766'

console.log(chrome.runtime);

chrome.runtime.onMessage.addListener(function (request, sender, callback) {
const xhr = new XMLHttpRequest();
xhr.addEventListener('loadend', function() {
Expand Down
35 changes: 35 additions & 0 deletions app/scripts/eow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
var results = $("#resultsList").find("li");
var index = 0;
var definitions = $.map(results,function(el){
if(el.children.length<3) return undefined;
var definition = {
'filename': window.location.href,
'text': el.children[0].innerText,
'translation': el.children[1].innerText.replace(/(?:\r\n|\r|\n)/g, '<br />')
};
var i = index;
$(el).find(".fukidashi").remove();
$(el).find(".tango_btn").unbind("click").bind("click",function(e) {
console.log(i);
chrome.runtime.sendMessage({
action: "link",
params: {
profile: 'sentence',
href: 'sentence_add:' + i
}
},function(response) {
$(el).find(".tango_btn").remove();
});
});
index += 1;
return definition;
});
chrome.runtime.sendMessage({
action: "set",
params: {
profile: 'sentence',
definitions: definitions
}
},function(response) {
console.log(response);
});
10 changes: 7 additions & 3 deletions build_zip.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#!/bin/sh

ZIP=yomichan.zip
rm yomichan_dicts.zip
7z a yomichan_dicts.zip yomi_base/languages/japanese/dictionary.db yomi_base/languages/chinese/cedict_ts.u8 yomi_base/languages/korean/dictionary.db

[ -f $ZIPFILE ] rm $ZIP
7z a yomichan.zip -xr\!\*.pyc yomichan.py yomi_base
rm yomichan_dict_european.zip
7z a yomichan_dict_european.zip pattern

rm tools.zip
7z a tools.zip tools yomi_base/mplayer/subfont.ttf
2 changes: 1 addition & 1 deletion build_zip_core.bat
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ rm yomichan.zip
7z a yomichan.zip -x!pattern -x!yomi_base/languages/spanish/es-eng.txt -x!yomi_base/languages/german/de-eng.txt -x!yomi_base/languages/german/de-eng.txt.db -x!yomi_base/languages/japanese/dictionary.zip -x!yomi_base/languages/japanese/dictionary.db -x!yomi_base/languages/chinese/cedict_ts.u8 -x!yomi_base/languages/korean/dictionary.db -x!yomi_base/languages/korean/dictionary.zip -x!yomi_base/mplayer/subfont.ttf yomichan.py UserList.py yomi_base
cd pysrt
7z a ..\yomichan.zip pysrt
cd ..
cd ..
5 changes: 5 additions & 0 deletions build_zip_core.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
rm yomichan.zip
7z a yomichan.zip -x!pattern -x!yomi_base/languages/spanish/es-eng.txt -x!yomi_base/languages/german/de-eng.txt -x!yomi_base/languages/german/de-eng.txt.db -x!yomi_base/languages/japanese/dictionary.zip -x!yomi_base/languages/japanese/dictionary.db -x!yomi_base/languages/chinese/cedict_ts.u8 -x!yomi_base/languages/korean/dictionary.db -x!yomi_base/languages/korean/dictionary.zip -x!yomi_base/mplayer/subfont.ttf yomichan.py UserList.py yomi_base
cd pysrt
7z a ../yomichan.zip pysrt
cd ..
9 changes: 3 additions & 6 deletions yomi_base/anki_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from yomi_base.errorHandler import ErrorHandler
from yomi_base.anki_server import AnkiConnect
from yomi_base import profiles
from yomi_base.constants import extensions
from anki.models import defaultModel,defaultField,defaultTemplate
from anki.utils import ids2str, intTime

Expand Down Expand Up @@ -136,18 +137,14 @@ def canAddNote(self, deckName, modelName, fields):


def createNote(self, deckName, modelName, fields, tags=list()):
self.noteCreate = "self.models().byName('{0}')".format(modelName)
model = self.models().byName(modelName)
if model is None:
return None

self.noteCreate = "self.decks().byName('{0}')".format(deckName)
deck = self.decks().byName(deckName)
if deck is None:
return None
self.noteCreate = "before create note"
note = anki.notes.Note(self.collection(), model)
self.noteCreate = "after create note"
self.note = note
note.model()['did'] = deck['id']
note.tags = tags
Expand Down Expand Up @@ -338,7 +335,7 @@ def loadAllTexts(self,rootDir=None):
mediadir = self.anki.collection().media.dir()
yomimedia = os.path.join(mediadir,rootDir)
def processFile(file,relDir):
if file[-4:] == '.txt':
if file[-4:] in extensions['text']:
path = os.path.join(relDir,file)
fullPath = u'::'.join(unicode(path).split(os.sep))
if fullPath in oldCache:
Expand Down Expand Up @@ -421,7 +418,7 @@ def onBeforeStateChange(state, oldState, *args):
if fileName == os.path.basename(os.path.splitext(file)[0]) and os.path.isfile(os.path.join(dirName,file)):
extension = file[file.rfind("."):]
yomichanInstance.window.currentFile.loadedExtensions.append(extension)
if extension not in [".txt",".srt",".mkv",".mp4"]:
if extension not in [".srt",".mkv",".mp4"] and extension not in extensions['text']:
openFile = os.path.join(dirName,file)
if sys.platform == 'linux2':
subprocess.call(["xdg*-open", openFile])
Expand Down
8 changes: 8 additions & 0 deletions yomi_base/anki_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,11 @@ def api_link(self,params):
for profile in self.yomisama.window.getSortedProfiles():
htmls[profile.name] = {'body':profile.defBody,'name':profile.displayedName};
return htmls

def api_set(self,params):
self.params = params
profile = self.yomisama.window.profiles[params["profile"]]
profile.definitions = params["definitions"]
profile.definitionType = 'list'
profile.updateDefinitions()
return profile.existsAlready
5 changes: 5 additions & 0 deletions yomi_base/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@
c = {
'appVersion': '0.17b',
}

extensions = {
'text': ('.json','.txt'),
'movie': ('.srt','.mkv','.mp4')
}
36 changes: 27 additions & 9 deletions yomi_base/deckManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@

import aqt
import anki.decks
import anki.utils
from anki.consts import *
import os,shutil
import copy
import yomi_base.anki_bridge
from yomi_base.constants import extensions

class DeckManager(anki.decks.DeckManager):
customDeckManager = True
Expand All @@ -32,24 +34,40 @@ def __init__(self,col,filecache):
self.changed = col.decks.changed
self.filecache = filecache

def cids(self, did, children=False):
def isYomiDeck(self, did):
return self.get(did)["name"].split("::")[0]=="Yomichan"

def get_yomi_cids(self, did):
deck = self.get(did)
if deck["name"].split("::")[0]=="Yomichan":
return self.col.db.list("select c.id from cards c join notes n on n.id = c.nid where " + yomi_base.anki_bridge.searchYomichanDeck(deck["name"]))
return self.col.db.list("select c.id from cards c join notes n on n.id = c.nid where " + yomi_base.anki_bridge.searchYomichanDeck(deck["name"]))

def cids(self, did, children=False):
if self.isYomiDeck(did):
return self.get_yomi_cids(did)
else:
return anki.decks.DeckManager.cids(self,did,children)

def get_card_ids(self, did, children=False, include_from_dynamic=False):
if self.isYomiDeck(did):
return self.get_yomi_cids(did)
else:
deck_ids = [did] + ([deck_id for _, deck_id in self.children(did)] if children else [])
request = "select id from cards where did in {}" + (" or odid in {}" if
include_from_dynamic else "")
parameters = (anki.utils.ids2str(deck_ids),) + ((anki.utils.ids2str(deck_ids),) if include_from_dynamic else tuple())
return self.col.db.list(request.format(*parameters))

def createDeck(self,path):
completePath = self.col.media.dir()
for i in path[:-1]:
completePath = os.path.join(completePath,i)
fullPath = os.path.join(completePath,path[-1])
if path[-1].endswith(".txt"):
if path[-1].endswith(extensions['text']):
if not os.path.isdir(completePath):
os.makedirs(completePath)
elif not os.path.isdir(fullPath):
os.makedirs(fullPath)
if path[-1].endswith(".txt") and not os.path.isfile(fullPath):
if path[-1].endswith(extensions['text']) and not os.path.isfile(fullPath):
f = open(fullPath,'w')
f.close()
return fullPath
Expand Down Expand Up @@ -86,8 +104,8 @@ def rename(self, g, name):
path2 = gname.split(u'::')
isYomichan = len(path) > 1 and path[0] == u'Yomichan'
isYomichan2 = len(path2) > 1 and path2[0] == u'Yomichan'
isFile = name.endswith('.txt')
isFile2 = gname.endswith('.txt')
isFile = name.endswith(extensions['text'])
isFile2 = gname.endswith(extensions['text'])
if isYomichan == isYomichan2 and isFile==isFile2:
anki.decks.DeckManager.rename(self,g,name)
elif isYomichan2 and not isYomichan:
Expand Down Expand Up @@ -120,7 +138,7 @@ def rename(self, g, name):
root_src_dir = self.col.media.dir()
for i in path2:
root_src_dir = os.path.join(root_src_dir,i)
if root_src_dir.endswith(".txt"):
if root_src_dir.endswith(extensions['text']):
shutil.move(root_src_dir, root_dst_dir)
else:
for src_dir, dirs, files in os.walk(root_src_dir):
Expand All @@ -136,7 +154,7 @@ def rename(self, g, name):
if gname in self.filecache:
self.filecache[name] = self.filecache[gname]
del self.filecache[gname]
elif not gname.endswith('.txt'):
elif not gname.endswith(extensions['text']):
for file in self.filecache:
if file.startswith(gname+'::'):
nname = file.replace(gname+'::',name+'::',1)
Expand Down
2 changes: 2 additions & 0 deletions yomi_base/profiles/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class GenericProfile:

def __init__(self,reader):
self.definitions = []
self.existsAlready = {}
self.reader = reader
self.textField = None
self.html = ""
Expand Down Expand Up @@ -94,6 +95,7 @@ def ankiIsFactValid(self, prfl, markup, index=None):
return result

def updateDefinitions(self,**options):
self.existsAlready = {}
defs = self.definitions[:]
if options.get('trim', True):
defs = defs[:self.reader.preferences['maxResults']]
Expand Down
21 changes: 14 additions & 7 deletions yomi_base/profiles/sentence.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class SentenceProfile(GenericProfile):
descriptor = "SENTENCES IN THIS TEXT"
languages = ["japanese","chinese","korean"]
sortIndex = 3
allowedTags = ['text','filename']
allowedTags = ['text','filename','translation']

def __init__(self,reader):
GenericProfile.__init__(self,reader)
Expand Down Expand Up @@ -101,7 +101,8 @@ def onAnchorClicked(self, url):
row = ''.join(map(unicode,tds))
self.definitions.append({
'text': row,
'filename': self.reader.state.filename
'filename': self.reader.state.filename,
'translation': ''
})
self.updateDefinitions()
self.reader.updateVocabDefs('sentence')
Expand All @@ -123,10 +124,12 @@ def onLookup(self,d,lengthMatched):
self.definitionType = "normal"
self.definitions = [{
'text': sentence,
'filename': self.reader.state.filename
'filename': self.reader.state.filename,
'translation': ''
},{
'text': line,
'filename': self.reader.state.filename
'filename': self.reader.state.filename,
'translation': ''
}]
self.updateDefinitions()
self.reader.updateVocabDefs('sentence')
Expand Down Expand Up @@ -154,18 +157,22 @@ def markup(self,definition):
def buildDefBody(self, definition, index, allowOverwrite):
links = ""
if self.ankiIsFactValid('sentence', self.markup(definition), index):
self.existsAlready[index] = False
links += '<a href="sentence_add:{0}"><img src="qrc:///img/img/icon_add_expression.png" align="right"></a>'.format(index)
else:
self.existsAlready[index] = True
#links += '<a href="sentence_add:{0}"><img src="qrc:///img/img/icon_add_expression.png" align="right"></a>'.format(index)
if allowOverwrite:
links += '<a href="sentence_overwrite:{0}"><img src="qrc:///img/img/icon_overwrite_expression.png" align="right"></a>'.format(index)

if self.definitionType == "normal":
if hasattr(self,'definitionType') and self.definitionType == "normal":
html = ("<b>Sentence: </b><br>" if index == 0 else "<b>Line: </b><br>")
else:
html = ""
html = html + u"""
<span class="sentence">{0}{1}<br></span>
<br clear="all">""".format(definition.get('text') or unicode(), links)
<span class="sentence">{0}{1}<br>{2}</span>
<br clear="all">""".format(definition.get('text') or unicode(),
links,definition.get('translation'))

#html = u"""<a href='kotonoha'>[Kotonoha]</a><br>""" + html

Expand Down
16 changes: 12 additions & 4 deletions yomi_base/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import sys
from yomi_base import profiles
from yomi_base.file_state import FileState
from yomi_base.constants import extensions


class Container(object):
Expand Down Expand Up @@ -268,13 +269,19 @@ def moveEvent(self, event):
def resizeEvent(self, event):
self.preferences['windowSize'] = event.size().width(), event.size().height()

def getFileFilter(self):
return ';;'.join(
['Text files (' +
' '.join(map(lambda x:'*'+x,extensions['text'])) +')',
'All files (*.*)'])


def onActionOpen(self):
filename = QtGui.QFileDialog.getOpenFileName(
parent=self,
caption='Select a file to open',
directory=self.state.filename,
filter='Text files (*.txt);;All files (*.*)'
filter=self.getFileFilter()
)
if filename:
self.openFile(filename)
Expand All @@ -284,7 +291,7 @@ def onActionSave(self):
parent=self,
caption='Select a file to save',
directory=self.state.filename,
filter='Text files (*.txt);;All files (*.*)'
filter=self.getFileFilter()
)
if filename:
self.saveFile(filename)
Expand All @@ -305,7 +312,7 @@ def onActionWordList(self):
filename = QtGui.QFileDialog.getOpenFileName(
parent=self,
caption='Select a word list file to import',
filter='Text files (*.txt);;All files (*.*)'
filter=self.getFileFilter()
)
if filename:
words = reader_util.extractWordList(filename)
Expand Down Expand Up @@ -649,7 +656,8 @@ def executeDefCommand(self, command, index):
def updateSampleMouseEvent(self, event):
cursor = self.textContent.cursorForPosition(event.pos())
self.state.scanPosition = cursor.position()
if event.buttons() & QtCore.Qt.MidButton or event.modifiers() & QtCore.Qt.ShiftModifier:
if event.buttons() & QtCore.Qt.MidButton or event.modifiers() &\
QtCore.Qt.ShiftModifier or event.buttons() & QtCore.Qt.XButton1:
self.updateSampleFromPosition()

def createAlias(self):
Expand Down

0 comments on commit 0bfd356

Please sign in to comment.