Refine parser

This commit is contained in:
Mygod
2016-03-12 14:39:00 +08:00
parent 0e0e65c45d
commit fb3f7429b7
3 changed files with 29 additions and 42 deletions
@@ -39,44 +39,35 @@
package com.github.shadowsocks.utils
import com.github.shadowsocks.database.Profile
import java.util.Locale
import android.net.Uri
import android.util.{Log, Base64}
import android.util.{Base64, Log}
import com.github.shadowsocks.database.Profile
object Parser {
val TAG = "ShadowParser"
private val pattern = "(?i)ss://([A-Za-z0-9+/=]+)".r
def generate (profile: Profile): String = "ss://" + Base64.encodeToString("%s:%s@%s:%d".formatLocal(Locale.ENGLISH,
profile.method, profile.password, profile.host, profile.remotePort).getBytes, Base64.NO_PADDING)
def parse (data: String): Option[Profile] = {
try {
Log.d(TAG, data)
val uri = Uri.parse(data.trim)
if (uri.getScheme == Scheme.SS) {
val encoded = data.replace(Scheme.SS + "://", "")
val content = new String(Base64.decode(encoded, Base64.NO_PADDING), "UTF-8")
val methodIdx = content.indexOf(':')
val passwordIdx = content.lastIndexOf('@')
val hostIdx = content.lastIndexOf(':')
val method = content.substring(0, methodIdx)
val password = content.substring(methodIdx + 1, passwordIdx)
val host = content.substring(passwordIdx + 1, hostIdx)
val port = content.substring(hostIdx + 1)
def findAll(data: String) = pattern.findAllMatchIn(data).map(m => try {
val content = new String(Base64.decode(m.group(1), Base64.NO_PADDING), "UTF-8")
val methodIdx = content.indexOf(':')
val passwordIdx = content.lastIndexOf('@')
val hostIdx = content.lastIndexOf(':')
val host = content.substring(passwordIdx + 1, hostIdx)
val profile = new Profile
profile.name = host
profile.host = host
profile.remotePort = port.toInt
profile.localPort = 1080
profile.method = method.toLowerCase
profile.password = password
return Some(profile)
}
} catch {
case ex : Exception => Log.e(TAG, "parser error", ex)// Ignore
}
None
}
val profile = new Profile
profile.name = host
profile.host = host
profile.remotePort = content.substring(hostIdx + 1).toInt
profile.method = content.substring(0, methodIdx).toLowerCase
profile.password = content.substring(methodIdx + 1, passwordIdx)
profile
} catch {
case ex: Exception =>
Log.e(TAG, "parser error: " + m.source, ex)// Ignore
null
}).filter(_ != null)
}