properly encode exported names when appropriate

This commit is contained in:
tibbi 2018-02-03 23:17:19 +01:00
parent e4718ffa82
commit 6fd7714725
2 changed files with 39 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package com.simplemobiletools.contacts.helpers package com.simplemobiletools.contacts.helpers
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import java.net.URLEncoder
// https://alvinalexander.com/java/jwarehouse/android/core/java/com/google/android/mms/pdu/QuotedPrintable.java.shtml // https://alvinalexander.com/java/jwarehouse/android/core/java/com/google/android/mms/pdu/QuotedPrintable.java.shtml
object QuotedPrintable { object QuotedPrintable {
@ -18,7 +19,7 @@ object QuotedPrintable {
if (b == ESCAPE_CHAR.toInt()) { if (b == ESCAPE_CHAR.toInt()) {
try { try {
if ('\r' == bytes[i + 1].toChar() && '\n' == bytes[i + 2].toChar()) { if ('\r' == bytes[i + 1].toChar() && '\n' == bytes[i + 2].toChar()) {
i += 2 i += 3
continue continue
} }
@ -40,4 +41,24 @@ object QuotedPrintable {
} }
return String(buffer.toByteArray()) return String(buffer.toByteArray())
} }
fun encode(value: String): String {
val result = StringBuilder()
value.forEach {
if (it == ' ') {
result.append(' ')
} else {
val urlEncoded = urlEncode(it.toString())
if (urlEncoded == it.toString()) {
val hex = String.format("%04x", it.toInt()).trimStart('0').toUpperCase()
result.append("=$hex")
} else {
result.append(urlEncoded)
}
}
}
return result.toString()
}
fun urlEncode(value: String) = URLEncoder.encode(value, "UTF-8").replace("+", " ").replace('%', '=')
} }

View File

@ -36,7 +36,7 @@ class VcfExporter {
for (contact in contacts) { for (contact in contacts) {
out.writeLn(BEGIN_VCARD) out.writeLn(BEGIN_VCARD)
out.writeLn(VERSION_2_1) out.writeLn(VERSION_2_1)
out.writeLn("$N:${contact.surname};${contact.firstName};${contact.middleName};;") out.writeLn("$N:${getNames(contact)}")
contact.phoneNumbers.forEach { contact.phoneNumbers.forEach {
out.writeLn("$TEL;${getPhoneNumberLabel(it.type)}:${it.value}") out.writeLn("$TEL;${getPhoneNumberLabel(it.type)}:${it.value}")
@ -91,6 +91,22 @@ class VcfExporter {
}) })
} }
private fun getNames(contact: Contact): String {
var firstName = contact.firstName
var surName = contact.surname
var middleName = contact.middleName
if (QuotedPrintable.urlEncode(firstName) != firstName
|| QuotedPrintable.urlEncode(surName) != surName
|| QuotedPrintable.urlEncode(middleName) != middleName) {
firstName = QuotedPrintable.encode(firstName)
surName = QuotedPrintable.encode(surName)
middleName = QuotedPrintable.encode(middleName)
}
return "$surName;$firstName;$middleName;;"
}
private fun getPhoneNumberLabel(type: Int) = when (type) { private fun getPhoneNumberLabel(type: Int) = when (type) {
CommonDataKinds.Phone.TYPE_MOBILE -> CELL CommonDataKinds.Phone.TYPE_MOBILE -> CELL
CommonDataKinds.Phone.TYPE_HOME -> HOME CommonDataKinds.Phone.TYPE_HOME -> HOME