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

@ -1,13 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet"> rel="stylesheet">
<link href="https://rawgit.com/summernote/summernote/master/dist/summernote.css" <link href="https://rawgit.com/summernote/summernote/master/dist/summernote.css"
rel="stylesheet"> rel="stylesheet">
</head> </head>
<body> <body>
<div id="summernote" style="width:100%;height:100%"></div> <div id="summernote" style="width:100%;height:100%"></div>
@ -15,27 +15,59 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <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 src="https://rawgit.com/summernote/summernote/master/dist/summernote.min.js"></script>
<script> <script>
$(document).ready(function() { function domToNode(domNode) {
$('#summernote').summernote({ if (domNode.nodeType == domNode.TEXT_NODE) {
height: 1200, return domNode.data;
focus: true, }
placeholder: '', if (domNode.nodeType != domNode.ELEMENT_NODE) {
toolbar: [ return false;
// [groupName, [list of button]] }
['style', ['bold', 'italic']], var nodeElement = {};
['para', ['ul', 'ol']], nodeElement.tag = domNode.tagName.toLowerCase();
['insert', ['link']], for (var i = 0; i < domNode.attributes.length; i++) {
['history', ['undo', 'redo']], var attr = domNode.attributes[i];
['other', ['codeview']] if (attr.name == 'href' || attr.name == 'src') {
], if (!nodeElement.attrs) {
callbacks: { nodeElement.attrs = {};
onInit: function(e) { }
$("#summernote").summernote("fullscreen.toggle"); 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,
placeholder: '',
toolbar: [
// [groupName, [list of button]]
['style', ['bold', 'italic']],
['para', ['ul', 'ol']],
['insert', ['link']],
['history', ['undo', 'redo']],
['other', ['codeview']]
],
callbacks: {
onInit: function (e) {
$("#summernote").summernote("fullscreen.toggle");
}
}
});
});
</script> </script>
</body> </body>
</html> </html>

View File

@ -8,13 +8,34 @@ class Api {
private val ApiBase = "https://api.telegra.ph/" private val ApiBase = "https://api.telegra.ph/"
fun getPage(id: String?, callback: (page: Page?) -> Unit) { fun getPage(id: String?, accessToken: String?, callback: (page: Page?) -> Unit) {
Bridge.get("${ApiBase}getPage/$id?return_content=true").asJsonObject { response, jsonObject, bridgeException -> 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()) if (jsonObject != null) callback(jsonObject.parsePage())
else callback(null) 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? { private fun JSONObject.parsePage(): Page? {
val result: Page = Page() val result: Page = Page()
if (optBoolean("ok", false)) { if (optBoolean("ok", false)) {

View File

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

View File

@ -12,34 +12,21 @@ import im.delight.android.webview.AdvancedWebView
class MainActivity : AppCompatActivity(), AdvancedWebView.Listener { 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 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 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 webView: AdvancedWebView? by lazy { findViewById(R.id.webView) as AdvancedWebView? }
private val editor: Editor? by lazy { findViewById(R.id.editor) as Editor? } 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 editorMode = true
private var canEdit = false
private var isEdit = false
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (intent.action == Intent.ACTION_VIEW && !intent.dataString.isNullOrBlank() && intent.dataString.contains("telegra.ph")) loadPage(intent.dataString.split("/").last()) setContentView(R.layout.activity_main)
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)
webView?.apply { webView?.apply {
setListener(this@MainActivity, this@MainActivity) setListener(this@MainActivity, this@MainActivity)
setMixedContentAllowed(true) setMixedContentAllowed(true)
@ -50,8 +37,54 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
isVerticalScrollBarEnabled = false isVerticalScrollBarEnabled = false
overScrollMode = View.OVER_SCROLL_NEVER overScrollMode = View.OVER_SCROLL_NEVER
} }
// Load if (intent.action == Intent.ACTION_VIEW && !intent.dataString.isNullOrBlank() && intent.dataString.contains("telegra.ph")) loadPage(intent.dataString.split("/").last())
Api().getPage(path) { page -> 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
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 { page?.let {
var html = htmlHead var html = htmlHead
html += "<h1>${it.title}</h1>" 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 if (it.content.isNullOrBlank()) html += it.description.replace("\n", "<br>") else html += it.content
html += htmlEnd html += htmlEnd
webView?.loadDataWithBaseURL(it.url, html, "text/html; charset=UTF-8", null, null) 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 { override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
super.onPrepareOptionsMenu(menu) super.onPrepareOptionsMenu(menu)
menu?.findItem(R.id.create)?.isVisible = !editorMode 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.publish)?.isVisible = editorMode
menu?.findItem(R.id.edit)?.isVisible = canEdit
return true return true
} }
@ -126,6 +161,30 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
loadEditor() loadEditor()
true 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 -> { R.id.bookmarks -> {
MaterialDialog.Builder(this) MaterialDialog.Builder(this)
.title(R.string.bookmarks) .title(R.string.bookmarks)
@ -152,7 +211,7 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
MaterialDialog.Builder(this) MaterialDialog.Builder(this)
.title(R.string.title_question) .title(R.string.title_question)
.input(getString(R.string.title_hint), "", { dialog, input -> .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() .show()
true true
@ -162,7 +221,7 @@ class MainActivity : AppCompatActivity(), AdvancedWebView.Listener {
shareIntent.action = Intent.ACTION_SEND shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text/plain" shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TITLE, webView?.title) 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))) startActivity(Intent.createChooser(shareIntent, getString(R.string.share)))
true true
} }

View File

@ -13,4 +13,10 @@ fun Context.addBookmark(entry: String) {
fun Context.deleteBookmark(path: String) { fun Context.deleteBookmark(path: String) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("bookmarks", bookmarks().filter { !it.contains(path) }.joinToString(separator = "+++;+++")).apply() 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:id="@+id/publish"
android:title="@string/publish" android:title="@string/publish"
app:showAsAction="ifRoom"/> app:showAsAction="ifRoom"/>
<item
android:id="@+id/edit"
android:title="@string/edit"
app:showAsAction="ifRoom"/>
<item <item
android:id="@+id/bookmarks" android:id="@+id/bookmarks"
android:title="@string/bookmarks" android:title="@string/bookmarks"

View File

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