Much progress

This commit is contained in:
Jan-Lk Else 2016-12-21 20:57:36 +01:00
parent c88dd9c944
commit b4d82140fe
10 changed files with 201 additions and 87 deletions

View File

@ -15,7 +15,40 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/summernote/summernote/master/dist/summernote.min.js"></script>
<script>
$(document).ready(function() {
function domToNode(domNode) {
if (domNode.nodeType == domNode.TEXT_NODE) {
return domNode.data;
}
if (domNode.nodeType != domNode.ELEMENT_NODE) {
return false;
}
var nodeElement = {};
nodeElement.tag = domNode.tagName.toLowerCase();
for (var i = 0; i < domNode.attributes.length; i++) {
var attr = domNode.attributes[i];
if (attr.name == 'href' || attr.name == 'src') {
if (!nodeElement.attrs) {
nodeElement.attrs = {};
}
nodeElement.attrs[attr.name] = attr.value;
}
}
if (domNode.childNodes.length > 0) {
nodeElement.children = [];
for (var ii = 0; ii < domNode.childNodes.length; ii++) {
var child = domNode.childNodes[ii];
nodeElement.children.push(domToNode(child));
}
}
return nodeElement;
}
function getNodeJson() {
window.android.getText(JSON.stringify(domToNode(document.getElementsByClassName('note-editable')[0]).children));
}
</script>
<script>
$(document).ready(function () {
$('#summernote').summernote({
height: 1200,
focus: true,
@ -29,13 +62,12 @@ $(document).ready(function() {
['other', ['codeview']]
],
callbacks: {
onInit: function(e) {
onInit: function (e) {
$("#summernote").summernote("fullscreen.toggle");
}
}
});
});
});
});
</script>
</body>
</html>

View File

@ -8,13 +8,34 @@ class Api {
private val ApiBase = "https://api.telegra.ph/"
fun getPage(id: String?, callback: (page: Page?) -> Unit) {
Bridge.get("${ApiBase}getPage/$id?return_content=true").asJsonObject { response, jsonObject, bridgeException ->
fun getPage(id: String?, accessToken: String?, callback: (page: Page?) -> Unit) {
Bridge.get("${ApiBase}getPage/$id?return_content=true" + if (accessToken != null) "&access_token=$accessToken" else "").asJsonObject { response, jsonObject, bridgeException ->
if (jsonObject != null) callback(jsonObject.parsePage())
else callback(null)
}
}
fun createPage(accessToken: String?, content: String?, title: String?, callback: (Page?) -> Unit) {
Bridge.get("${ApiBase}createPage?access_token=$accessToken&title=%s&content=$content&return_content=true", title).asJsonObject { response, jsonObject, bridgeException ->
if (jsonObject != null) callback(jsonObject.parsePage())
else callback(null)
}
}
fun editPage(accessToken: String?, path: String?, content: String?, title: String?, callback: (Page?) -> Unit) {
Bridge.get("${ApiBase}editPage/$path?access_token=$accessToken&title=%s&content=$content&return_content=true", title).asJsonObject { response, jsonObject, bridgeException ->
if (jsonObject != null) callback(jsonObject.parsePage())
else callback(null)
}
}
fun createAccount(callback: (accessToken: String?) -> Unit) {
Bridge.get("${ApiBase}createAccount?short_name=teleposter").asJsonObject { response, jsonObject, bridgeException ->
if (jsonObject != null) callback(jsonObject.optJSONObject("result")?.optString("access_token"))
else callback(null)
}
}
private fun JSONObject.parsePage(): Page? {
val result: Page = Page()
if (optBoolean("ok", false)) {

View File

@ -9,21 +9,17 @@ import android.webkit.WebView
import android.webkit.WebViewClient
class Editor : WebView {
private var text = ""
internal var context: Context
private var getCallback: (json: String?) -> Unit? = {}
constructor(context: Context) : super(context) {
this.context = context
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
this.context = context
init()
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
this.context = context
init()
}
@ -38,8 +34,8 @@ class Editor : WebView {
private inner class MyJavaScriptInterface {
@JavascriptInterface
fun getText(html: String) {
text = html
fun getText(json: String) {
getCallback(json)
}
}
@ -53,19 +49,9 @@ class Editor : WebView {
this.loadUrl("javascript:$('#summernote').summernote('code', '" + html.replace("'", "\\'") + "');")
}
fun getText(): String {
text = "P/%TE5XpkAijBc%LjA;_-pZcbiU25E6feX5y/n6qxCTmhprLrqC3H%^hU!%q2,k'm`SHheoW^'mQ~zW93,C?~GtYk!wi/&'3KxW8"
this.loadUrl("javascript:window.android.getText" + "(document.getElementsByClassName('note-editable')[0].innerHTML);")
var i = 0
try {
while (text == "P/%TE5XpkAijBc%LjA;_-pZcbiU25E6feX5y/n6qxCTmhprLrqC3H%^hU!%q2,k'm`SHheoW^'mQ~zW93,C?~GtYk!wi/&'3KxW8" && i < 100) {
Thread.sleep(50)
i++
}
} catch (e: Exception) {
text = ""
}
return text
fun getText(callback: (json: String?) -> Unit) {
getCallback = callback
this.loadUrl("javascript:getNodeJson();")
}
}

View File

@ -12,34 +12,21 @@ import im.delight.android.webview.AdvancedWebView
class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
private val TELEGRAPH = "http://telegra.ph/"
private val htmlHead = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"><style> * { max-width: 100%; height: auto; word-break: break-all; word-break: break-word; }</style></head><body>"
private val htmlEnd = "<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script></body></html>"
private val webView: AdvancedWebView? by lazy { findViewById(R.id.webView) as AdvancedWebView? }
private val editor: Editor? by lazy { findViewById(R.id.editor) as Editor? }
private var url = ""
private var currentUrl = ""
private var currentPage: Page? = null
private var editorMode = true
private var canEdit = false
private var isEdit = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.action == Intent.ACTION_VIEW && !intent.dataString.isNullOrBlank() && intent.dataString.contains("telegra.ph")) loadPage(intent.dataString.split("/").last())
else loadEditor()
}
private fun loadEditor() {
editorMode = true
invalidateOptionsMenu()
// Init
setContentView(R.layout.main_write)
}
private fun loadPage(path: String) {
editorMode = false
invalidateOptionsMenu()
// Init
setContentView(R.layout.main_read)
setContentView(R.layout.activity_main)
webView?.apply {
setListener(this@MainActivity, this@MainActivity)
setMixedContentAllowed(true)
@ -50,8 +37,54 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
isVerticalScrollBarEnabled = false
overScrollMode = View.OVER_SCROLL_NEVER
}
if (intent.action == Intent.ACTION_VIEW && !intent.dataString.isNullOrBlank() && intent.dataString.contains("telegra.ph")) loadPage(intent.dataString.split("/").last())
else loadEditor()
}
private fun loadEditor(path: String? = null) {
runOnUiThread {
editorMode = true
canEdit = false
isEdit = false
invalidateOptionsMenu()
editor?.visibility = View.VISIBLE
webView?.visibility = View.GONE
currentPage = null
// Load
Api().getPage(path) { page ->
if (path != null) Api().getPage(path, accessToken()) { page ->
runOnUiThread {
isEdit = true
currentPage = page
editor?.setText(page?.content ?: "")
}
}
}
}
private fun loadPage(path: String) {
runOnUiThread {
editorMode = false
canEdit = false
invalidateOptionsMenu()
webView?.visibility = View.VISIBLE
editor?.visibility = View.GONE
currentPage = null
// Load
Api().getPage(path, accessToken()) { page ->
showPage(page)
}
}
}
private fun showPage(page: Page?) {
runOnUiThread {
editorMode = false
canEdit = page?.can_edit ?: false
invalidateOptionsMenu()
webView?.visibility = View.VISIBLE
editor?.visibility = View.GONE
currentPage = page
// Show
page?.let {
var html = htmlHead
html += "<h1>${it.title}</h1>"
@ -61,7 +94,7 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
if (it.content.isNullOrBlank()) html += it.description.replace("\n", "<br>") else html += it.content
html += htmlEnd
webView?.loadDataWithBaseURL(it.url, html, "text/html; charset=UTF-8", null, null)
url = it.url
currentUrl = it.url
}
}
}
@ -116,7 +149,9 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
super.onPrepareOptionsMenu(menu)
menu?.findItem(R.id.create)?.isVisible = !editorMode
menu?.findItem(R.id.share)?.isVisible = !editorMode
menu?.findItem(R.id.publish)?.isVisible = editorMode
menu?.findItem(R.id.edit)?.isVisible = canEdit
return true
}
@ -126,6 +161,30 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
loadEditor()
true
}
R.id.publish -> {
editor?.getText { json ->
MaterialDialog.Builder(this)
.title(R.string.title_question)
.input(getString(R.string.title_hint), currentPage?.title ?: "", { dialog, title ->
if (accessToken().isNullOrBlank()) {
Api().createAccount { accessToken ->
if (accessToken != null) saveAccessToken(accessToken)
if (isEdit) Api().editPage(accessToken(), currentPage?.path, json, title.toString()) { page -> showPage(page) }
else Api().createPage(accessToken(), json, title.toString()) { page -> showPage(page) }
}
} else {
if (isEdit) Api().editPage(accessToken(), currentPage?.path, json, title.toString()) { page -> showPage(page) }
else Api().createPage(accessToken(), json, title.toString()) { page -> showPage(page) }
}
})
.show()
}
true
}
R.id.edit -> {
loadEditor(currentPage?.path)
true
}
R.id.bookmarks -> {
MaterialDialog.Builder(this)
.title(R.string.bookmarks)
@ -152,7 +211,7 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
MaterialDialog.Builder(this)
.title(R.string.title_question)
.input(getString(R.string.title_hint), "", { dialog, input ->
addBookmark("${(if (webView?.url != "about:blank") webView?.url ?: url else url).split("/").last()}xxx;xxx$input")
addBookmark("${(if (webView?.url != "about:blank") webView?.url ?: currentUrl else currentUrl).split("/").last()}xxx;xxx$input")
})
.show()
true
@ -162,7 +221,7 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TITLE, webView?.title)
shareIntent.putExtra(Intent.EXTRA_TEXT, if (webView?.url != "about:blank") webView?.url ?: url else url)
shareIntent.putExtra(Intent.EXTRA_TEXT, currentUrl)
startActivity(Intent.createChooser(shareIntent, getString(R.string.share)))
true
}

View File

@ -14,3 +14,9 @@ fun Context.addBookmark(entry: String) {
fun Context.deleteBookmark(path: String) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("bookmarks", bookmarks().filter { !it.contains(path) }.joinToString(separator = "+++;+++")).apply()
}
fun Context.accessToken(): String? = PreferenceManager.getDefaultSharedPreferences(this).getString("accessToken", null)
fun Context.saveAccessToken(token: String) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("accessToken", token).apply()
}

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<telegra.ph.Editor
android:id="@+id/editor"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<im.delight.android.webview.AdvancedWebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"/>
</LinearLayout>

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<im.delight.android.webview.AdvancedWebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginStart="16dp"/>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<telegra.ph.Editor
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/editor"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

View File

@ -9,6 +9,10 @@
android:id="@+id/publish"
android:title="@string/publish"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/edit"
android:title="@string/edit"
app:showAsAction="ifRoom"/>
<item
android:id="@+id/bookmarks"
android:title="@string/bookmarks"

View File

@ -13,4 +13,5 @@
<string name="delete">Delete</string>
<string name="delete_question">Do you really want to delete this?</string>
<string name="publish">Publish</string>
<string name="edit">Edit</string>
</resources>