diff --git a/BotLibre/build.gradle b/BotLibre/build.gradle index 5e14ced4932a910a9064c5d2a471dafeb88e9285..a4bbee50c84428507c792bf978676f0ff6fe17a8 100644 --- a/BotLibre/build.gradle +++ b/BotLibre/build.gradle @@ -2,17 +2,6 @@ apply plugin: 'com.huawei.ohos.app' ohos { - signingConfigs { - debug { - storeFile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.p12') - storePassword '00000018FFA5B0DB00CC2DFB0A89B137185B03D94C95D55C2F0148EC9FCED9F4A791FF9785DC1833' - keyAlias = 'debugKey' - keyPassword '00000018D501A8D4DB4D6582A8035A2E4252EF3EC44C534D576759AC04E7BCBBF3E3A5A8070C2E7E' - signAlg = 'SHA256withECDSA' - profile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_sdk_890086000102149657.p7b') - certpath file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.cer') - } - } compileSdkVersion 6 defaultConfig { compatibleSdkVersion 5 diff --git a/BotLibre/entry/src/main/config.json b/BotLibre/entry/src/main/config.json index 73625b375b260708b7108ab1a1e24134225f04f6..017e9a53644d50c98394a5b787dd4618d226b5fa 100644 --- a/BotLibre/entry/src/main/config.json +++ b/BotLibre/entry/src/main/config.json @@ -115,24 +115,54 @@ "name": "ohos.permission.ACCESS_BIOMETRIC_INTERNAL" }, { + "name": "ohos.permission.READ_USER_STORAGE", "reason": "Read User Storage", - "name": "ohos.permission.READ_USER_STORAGE" + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Camera", - "name": "ohos.permission.READ_MEDIA" + "name": "ohos.permission.READ_MEDIA", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Media", - "name": "ohos.permission.MEDIA_LOCATION" + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.WRITE_USER_STORAGE", - "reason": "get WRITE_USER_STORAGE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.MICROPHONE", - "reason": "get MICROPHONE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } } ] } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java index fa87008d9337394bdc61592cc11c48d5806d9798..1b2e369246c78a388e4bb12014769417654545b7 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java @@ -23,11 +23,9 @@ package org.botlibre.sdk; * http://www.botlibre.com */ public class BOTlibreCredentials extends Credentials { - public static String DOMAIN = "www.botlibre.com"; - //public static String DOMAIN = "192.168.0.21:9080"; - public static String APP = ""; - //public static String APP = "/botlibre"; - public static String PATH = "/rest/api"; + public static final String DOMAIN = "www.botlibre.com"; + public static final String APP = ""; + public static final String PATH = "/rest/api"; public BOTlibreCredentials(String applicationId) { this.host = DOMAIN; diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/MainAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/MainAbility.java index 0db311c6c478c662a5d761c77713f52fda8b62b5..da3cb81472e57eb60ff034b291700487217d7b1a 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/MainAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/MainAbility.java @@ -8,10 +8,8 @@ import ohos.agp.components.Component; import ohos.agp.components.DirectionalLayout; import ohos.agp.components.LayoutScatter; import ohos.agp.components.Text; -import ohos.agp.components.TextField; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.CommonDialog; -import ohos.agp.window.dialog.IDialog; import ohos.agp.window.dialog.PopupDialog; import ohos.agp.window.service.Display; import ohos.agp.window.service.DisplayAttributes; @@ -33,11 +31,7 @@ import org.botlibre.sdk.ability.LibreAbility; import org.botlibre.sdk.ability.ListTemplateView; import org.botlibre.sdk.ability.LoginAbility; import org.botlibre.sdk.ability.actions.HttpAction; -import org.botlibre.sdk.ability.actions.HttpConnectAction; -import org.botlibre.sdk.ability.actions.HttpFetchAction; import org.botlibre.sdk.ability.actions.HttpFetchActionOffline; -import org.botlibre.sdk.ability.actions.HttpFetchOrCreateAction; -import org.botlibre.sdk.ability.actions.HttpGetInstancesAction; import org.botlibre.sdk.ability.adapter.SpinnerAdapter; import org.botlibre.sdk.ability.avatar.AvatarSelection; import org.botlibre.sdk.ability.dialog.LanguageDialogBuilder; @@ -45,21 +39,16 @@ import org.botlibre.sdk.ability.dialog.SpinnerDialogBuilder; import org.botlibre.sdk.ability.listener.LanguageListener; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.ability.war.StartWarAbility; -import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.AvatarMedia; -import org.botlibre.sdk.config.BotModeConfig; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChannelConfig; import org.botlibre.sdk.config.DomainConfig; import org.botlibre.sdk.config.ForumConfig; import org.botlibre.sdk.config.ForumPostConfig; -import org.botlibre.sdk.config.GraphicConfig; import org.botlibre.sdk.config.InstanceConfig; import org.botlibre.sdk.config.IssueConfig; import org.botlibre.sdk.config.LearningConfig; import org.botlibre.sdk.config.OfflineTemplateConfig; import org.botlibre.sdk.config.ResponseConfig; -import org.botlibre.sdk.config.ScriptConfig; import org.botlibre.sdk.config.ScriptSourceConfig; import org.botlibre.sdk.config.UserConfig; import org.botlibre.sdk.config.VoiceConfig; @@ -67,7 +56,6 @@ import org.botlibre.sdk.config.WebMediumConfig; import org.botlibre.sdk.micro.MicroConnection; import org.botlibre.sdk.util.PreferencesUtils; -import javax.swing.text.View; import java.awt.*; import java.io.File; import java.util.ArrayList; @@ -80,29 +68,47 @@ import static ohos.agp.components.Component.HIDE; import static ohos.agp.components.Component.VISIBLE; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; -public class MainAbility extends LibreAbility implements SelectListener, LanguageListener, Component.TouchEventListener { +/** + * MainAbility + * + * @since 2021-04-25 + */ +public class MainAbility extends LibreAbility implements SelectListener, LanguageListener, + Component.TouchEventListener { + /** + * DEBUG + */ public static final boolean DEBUG = false; - public static final boolean ADULT = false; /** * Enter your application ID here. * You can get an application ID from any of the services websites (Bot Libre, Bot Libre for Business) */ - public static String applicationId = "enter your application id here"; + private static final String applicationId = "enter your application id here"; /** * Configure your connection credentials here. * Choose which service provider you wish to connect to. */ - public static SDKConnection connection, localConnection, remoteConnection; + private static SDKConnection connection; + /** + * Configure your connection credentials here. + * Choose which service provider you wish to connect to. + */ + private static SDKConnection localConnection; + /** + * Configure your connection credentials here. + * Choose which service provider you wish to connect to. + */ + private static SDKConnection remoteConnection; /** * To launch into a specific domain, enter the domain id here. */ - public static String domainId = null; - public static DomainConfig domain; - public static String defaultType = "Bots"; - public static boolean showAds = true; + private static String domainId = null; + private static DomainConfig domain; + private static String defaultType = "Bots"; + private static boolean showAds = true; /** * Choose your service provider using the correct credentials. @@ -111,37 +117,33 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag localConnection = new MicroConnection(new BOTlibreCredentials(applicationId)); remoteConnection = new SDKConnection(new BOTlibreCredentials(applicationId)); connection = remoteConnection; - if (domainId != null) { - domain = new DomainConfig(); - domain.id = domainId; - connection.setDomain(domain); - } + domain = new DomainConfig(); + domain.id = domainId; + connection.setDomain(domain); if (DEBUG) { showAds = false; connection.setDebug(true); } } - public static String WEBSITE = "https://www.botlibre.com"; + /** + * WEBSITEHTTPS + */ public static final String WEBSITEHTTPS = "https://www.botlibre.com"; - public static String SERVER = "botlibre.com"; /** * If you are building a single instance app, then you can set the instance id or name here, * and use this to launch it. */ - public static String launchInstanceId = ""; // i.e. "171" - public static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" - public static String website = "https://www.botlibre.com"; - public static String prefix = "Bot"; - public static String launchSelfScriptID = ""; - public static String launchGreetingScriptID = ""; + private static String launchInstanceId = ""; // i.e. "171" + private static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" + private static String website = "https://www.botlibre.com"; /** * If you are building a single instance app, then you can set the launchType to * have this launch the bot, forum, or channel. */ - public static LaunchType launchType = LaunchType.Browse; + private static LaunchType launchType = LaunchType.Browse; @Override public void selectItem(String select) { @@ -152,279 +154,752 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag spin.setText(select); } - @Override - public void selectLanguageItem(String select) { - languageselect.setText(select); + @Override + public void selectLanguageItem(String select) { + languageselect.setText(select); + } + + @Override + public boolean onTouchEvent(Component component, TouchEvent touchEvent) { + switch (touchEvent.getAction()) { + case TouchEvent.PRIMARY_POINT_DOWN: + break; + default: + } + return true; + } + + /** + * LaunchType + * + * @since 2021-05-10 + */ + public enum LaunchType {Browse, Bot, Forum, Channel} + + private static boolean online = true; + + private static boolean handsFreeSpeech = true; + private static boolean listenInBackground = false; + private static boolean micConfig = true; + + // selected image from the listView of the offline Templates bots + private static int offlineSelectedImage; + + private static boolean sound = true; + private static boolean disableVideo; + private static boolean webm = true; + private static boolean hd; + private static boolean deviceVoice; + private static boolean customVoice; + private static boolean translate; + + private static boolean offlineSpeech = false; + + private static WebMediumConfig instance; + private static ForumPostConfig post; + private static IssueConfig issue; + private static UserConfig user; + private static UserConfig viewUser; + private static String type = "Bots"; + private static VoiceConfig voice = new VoiceConfig(); + private static LearningConfig learning = new LearningConfig(); + private static ResponseConfig response; + private static ScriptSourceConfig script; + private static String conversation; + private static String template = ""; + private static Object[] tags; + private static Object[] categories; + private static Object[] forumTags; + private static Object[] forumCategories; + private static Object[] channelTags; + private static Object[] channelCategories; + private static int volume; + + private static String contentRating; + private static Object[] domainTags; + private static Object[] domainCategories; + + private static String nameOfAvatar; + + private static Object[] graphicTags; + private static Object[] graphicCategories; + private static boolean showImages = true; + private static BrowseConfig browsePosts = null; + private static List instances = new ArrayList(); + private static List posts = new ArrayList(); + private static MainAbility current; + private static boolean browsing; + private static boolean searching; + private static boolean searchingPosts; + private static boolean importingBotScript = false; + private static boolean importingBotLog = false; + private static String[] languages = { + "Default", + "af - Afrikaans", "sq - Albanian", "ar - Arabic", "hy - Armenian", "az - Azerbaijani", + "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - Bulgarian", + "ca - Catalan", "zh - Chinese", "hr - Croatian", "cs - Czech", "da - Danish", "nl - Dutch", "en - English", "et - Estonian", "fi - Finnish", "fr - French", + "gl - Galician", "ka - Georgian", "de - German", "el - Greek", "gu - Gujarati", "ht - Haitian", "he - Hebrew", "hi - Hindi", "hu - Hungarian", + "is - Icelandic", "id - Indonesian", "ga - Irish", "it - Italian", "ja - Japanese", "kn - Kannada", "kk - Kazakh", "ky - Kirghiz", "ko - Korean", + "la - Latin", "lv - Latvian", "lt - Lithuanian", "mk - Macedonian", "mg - Malagasy", "ms - Malay", "mt - Maltese", "mn - Mongolian", "no - Norwegian", + "fa - Persian", "pl - Polish", "pt - Portuguese", "pa - Punjabi", "ro - Romanian", "ru - Russian", + "sr - Serbian", "si - Sinhalese", "sk - Slovak", "sl - Slovenian", "es - Spanish", "sw - Swahili", "sv - Swedish", + "tl - Tagalog", "tg - Tajik", "ta - Tamil", "tt - Tatar", "th - Thai", "tr - Turkish", + "udm - Udmurt", "uk - Ukrainian", "ur - Urdu", "uz - Uzbek", "vi - Vietnamese", "cy - Welsh" + }; + /** + * servers + */ + public static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; + /** + * types + */ + private static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; + /** + * contentRatings + */ + private static String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; + /** + * inputTypes + */ + public static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; + + + Menu menu; + private static int templateID; + private Button spin; + private Button createInstanceButton; + private Button browseButton; + private Button menuButton; + private Button loginButton; + private Button chatButton; + private Button logoutButton; + private Button viewUserButton; + private Button helpButton; + + /** + * getTypes + * + * @return dd + */ + public static String[] getTypes() { + return types.clone(); + } + + public static void setTypes(String[] type) { + types = type.clone(); + } + + public static String[] getContentRatings() { + return contentRatings.clone(); + } + + public static void setContentRatings(String[] contentRating) { + contentRatings = contentRating.clone(); + } + + public static String getTemplate() { + return template; + } + + public static void setTemplate(String template) { + MainAbility.template = template; + } + + public static UserConfig getViewUser() { + return viewUser; + } + + public static void setViewUser(UserConfig viewUser) { + MainAbility.viewUser = viewUser; + } + + public static LearningConfig getLearning() { + return learning; + } + + public static void setLearning(LearningConfig learning) { + MainAbility.learning = learning; + } + + public static int getOfflineSelectedImage() { + return offlineSelectedImage; + } + + public static void setOfflineSelectedImage(int offlineSelectedImage) { + MainAbility.offlineSelectedImage = offlineSelectedImage; + } + + public static boolean isCustomVoice() { + return customVoice; + } + + public static void setCustomVoice(boolean customVoice) { + MainAbility.customVoice = customVoice; + } + + public static boolean isMicConfig() { + return micConfig; + } + + public static void setMicConfig(boolean micConfig) { + MainAbility.micConfig = micConfig; + } + + public static int getTemplateID() { + return templateID; + } + + public static void setTemplateID(int templateID) { + MainAbility.templateID = templateID; + } + + public static String getLaunchInstanceId() { + return launchInstanceId; + } + + public static void setLaunchInstanceId(String launchInstanceId) { + MainAbility.launchInstanceId = launchInstanceId; + } + + public static String getLaunchInstanceName() { + return launchInstanceName; + } + + public static void setLaunchInstanceName(String launchInstanceName) { + MainAbility.launchInstanceName = launchInstanceName; + } + + public static boolean isOfflineSpeech() { + return offlineSpeech; + } + + public static void setOfflineSpeech(boolean offlineSpeech) { + MainAbility.offlineSpeech = offlineSpeech; + } + + public static boolean isImportingBotLog() { + return importingBotLog; + } + + public static void setImportingBotLog(boolean importingBotLog) { + MainAbility.importingBotLog = importingBotLog; + } + + public static boolean isImportingBotScript() { + return importingBotScript; + } + + public static void setImportingBotScript(boolean importingBotScript) { + MainAbility.importingBotScript = importingBotScript; + } + + public static SDKConnection getRemoteConnection() { + return remoteConnection; + } + + public static void setRemoteConnection(SDKConnection remoteConnection) { + MainAbility.remoteConnection = remoteConnection; + } + + public static String getDefaultType() { + return defaultType; + } + + public static void setDefaultType(String defaultType) { + MainAbility.defaultType = defaultType; + } + + public static DomainConfig getDomain() { + return domain; + } + + public static void setDomain(DomainConfig domain) { + MainAbility.domain = domain; + } + + public static String getDomainId() { + return domainId; + } + + public static void setDomainId(String domainId) { + MainAbility.domainId = domainId; + } + + public static SDKConnection getConnection() { + return connection; + } + + public static void setConnection(SDKConnection connection) { + MainAbility.connection = connection; + } + + public static boolean isSound() { + return sound; + } + + public static void setSound(boolean sound) { + MainAbility.sound = sound; + } + + public static boolean isDeviceVoice() { + return deviceVoice; + } + + public static void setDeviceVoice(boolean deviceVoice) { + MainAbility.deviceVoice = deviceVoice; + } + + public static boolean isHd() { + return hd; + } + + public static void setHd(boolean hd) { + MainAbility.hd = hd; + } + + public static boolean isWebm() { + return webm; + } + + public static void setWebm(boolean webm) { + MainAbility.webm = webm; + } + + public static boolean isDisableVideo() { + return disableVideo; + } + + public static void setDisableVideo(boolean disableVideo) { + MainAbility.disableVideo = disableVideo; + } + + public static boolean isTranslate() { + return translate; + } + + public static void setTranslate(boolean translate) { + MainAbility.translate = translate; + } + + public static boolean isListenInBackground() { + return listenInBackground; + } + + public static void setListenInBackground(boolean listenInBackground) { + MainAbility.listenInBackground = listenInBackground; + } + + public static String[] getLanguages() { + return languages.clone(); + } + + public static void setLanguages(String[] language) { + languages = language.clone(); + } + + public static int getVolume() { + return volume; + } + + public static void setVolume(int volum) { + volume = volum; + } + + public static boolean isSearchingPosts() { + return searchingPosts; + } + + public static void setSearchingPosts(boolean searchingPost) { + searchingPosts = searchingPost; + } + + public static String getConversation() { + return conversation; + } + + public static void setConversation(String conversatio) { + conversation = conversatio; + } + + public static VoiceConfig getVoice() { + return voice; + } + + public static void setVoice(VoiceConfig voice) { + MainAbility.voice = voice; + } + + public static String getContentRating() { + return contentRating; + } + + public static void setContentRating(String contentRating) { + MainAbility.contentRating = contentRating; + } + + public static boolean isShowImages() { + return showImages; + } + + public static void setShowImages(boolean showImages) { + MainAbility.showImages = showImages; + } + + public static MainAbility getCurrent() { + return current; + } + + public static void setCurrent(MainAbility current) { + MainAbility.current = current; + } + + public static String getNameOfAvatar() { + return nameOfAvatar; + } + + public static void setNameOfAvatar(String nameOfAvatar) { + MainAbility.nameOfAvatar = nameOfAvatar; + } + + public static BrowseConfig getBrowsePosts() { + return browsePosts; + } + + public static void setBrowsePosts(BrowseConfig browsePosts) { + MainAbility.browsePosts = browsePosts; + } + + public static List getPosts() { + return posts; + } + + public static void setPosts(List posts) { + MainAbility.posts = posts; + } + + public static ForumPostConfig getPost() { + return post; + } + + public static void setPost(ForumPostConfig post) { + MainAbility.post = post; + } + + public static List getInstances() { + return instances; + } + + public static void setInstances(List instances) { + MainAbility.instances = instances; + } + + public static IssueConfig getIssue() { + return issue; + } + + public static void setIssue(IssueConfig issue) { + MainAbility.issue = issue; + } + + public static String getType() { + return type; + } + + public static void setType(String type) { + MainAbility.type = type; + } + + /** + * getGraphicCategories + * + * @return ds + */ + public static Object[] getGraphicCategories() { + return graphicCategories.clone(); + } + + /** + * setGraphicCategories + * + * @param graphicCategorie + */ + public static void setGraphicCategories(Object[] graphicCategorie) { + if (graphicCategorie != null) { + graphicCategories = graphicCategorie.clone(); + } + } + + public static Object[] getGraphicTags() { + return graphicTags.clone(); + } + + /** + * setGraphicTags + * + * @param graphicTag + */ + public static void setGraphicTags(Object[] graphicTag) { + if (graphicTag != null) { + graphicTags = graphicTag.clone(); + } + } + + /** + * getDomainCategories + * + * @return ds + */ + public static Object[] getDomainCategories() { + return domainCategories.clone(); + } + + /** + * setDomainCategories + * + * @param domainCategorie + */ + public static void setDomainCategories(Object[] domainCategorie) { + if (domainCategorie != null) { + domainCategories = domainCategorie.clone(); + } + } + + /** + * getDomainTags + * + * @return dd + */ + public static Object[] getDomainTags() { + return domainTags.clone(); + } + + /** + * setDomainTags + * + * @param domainTag + */ + public static void setDomainTags(Object[] domainTag) { + if (domainTag != null) { + domainTags = domainTag.clone(); + + } + } + + /** + * getChannelCategories + * + * @return dd + */ + public static Object[] getChannelCategories() { + return channelCategories.clone(); + } + + /** + * setChannelCategories + * + * @param channelCategorie + */ + public static void setChannelCategories(Object[] channelCategorie) { + if (channelCategorie != null) { + channelCategories = channelCategorie.clone(); + } + } + + /** + * getChannelTags + * + * @return dd + */ + public static Object[] getChannelTags() { + return channelTags.clone(); + } + + /** + * setChannelTags + * + * @param channelTag + */ + public static void setChannelTags(Object[] channelTag) { + if (channelTag != null) { + channelTags = channelTag.clone(); + } + } + + /** + * getForumCategories + * + * @return dd + */ + public static Object[] getForumCategories() { + return forumCategories.clone(); + } + + /** + * setForumCategories + * + * @param forumCategorie + */ + public static void setForumCategories(Object[] forumCategorie) { + if (forumCategorie != null) { + forumCategories = forumCategorie.clone(); + } + } + + /** + * getForumTags + * + * @return sdd + */ + public static Object[] getForumTags() { + return forumTags.clone(); + } + + public static void setForumTags(Object[] forumTag) { + forumTags = forumTag.clone(); + } + + /** + * getCategories + * + * @return dd + */ + public static Object[] getCategories() { + return categories.clone(); + } + + /** + * setCategories + * + * @param categorie + */ + public static void setCategories(Object[] categorie) { + categories = categorie.clone(); + } + + /** + * getTags + * + * @return dd + */ + public static Object[] getTags() { + return tags.clone(); + } + + /** + * setTags + * + * @param tag + */ + public static void setTags(Object[] tag) { + tags = tag.clone(); + } + + /** + * getUser + * + * @return dd + */ + public static UserConfig getUser() { + return user; + } + + /** + * setUser + * + * @param user + */ + public static void setUser(UserConfig user) { + MainAbility.user = user; + } + + /** + * getInstance + * + * @return dd + */ + public static WebMediumConfig getInstance() { + return instance; + } + + /** + * setInstance + * + * @param instance + */ + public static void setInstance(WebMediumConfig instance) { + MainAbility.instance = instance; + } + + /** + * isSearching + * + * @return dd + */ + public static boolean isSearching() { + return searching; + } + + /** + * setSearching + * + * @param searching + */ + public static void setSearching(boolean searching) { + MainAbility.searching = searching; } - @Override - public boolean onTouchEvent(Component component, TouchEvent touchEvent) { - switch (touchEvent.getAction()) { - case TouchEvent.PRIMARY_POINT_DOWN: - // Check whether the user pressed on the pointer. -// execcontentinfo.setScrollable(true); -// notifyAll(); - break; - default: - } - return true; + /** + * isBrowsing + * + * @return dd + */ + public static boolean isBrowsing() { + return browsing; } - public enum LaunchType {Browse, Bot, Forum, Channel} - - public static boolean online = true; + /** + * setBrowsing + * + * @param browsing + */ + public static void setBrowsing(boolean browsing) { + MainAbility.browsing = browsing; + } - public static boolean handsFreeSpeech = true; - public static boolean listenInBackground = false; - public static boolean micConfig = true; + /** + * isHandsFreeSpeech + * + * @return dd + */ + public static boolean isHandsFreeSpeech() { + return handsFreeSpeech; + } - // selected image from the listView of the offline Templates bots - public static int offlineSelectedImage; - - public static boolean hasRequestAvatar; - public static boolean sound = true; - public static boolean disableVideo; - public static boolean webm = true; - public static boolean hd; - public static boolean deviceVoice; - public static boolean customVoice; - public static boolean translate; - - public static boolean offlineSpeech = false; - - public static GraphicConfig gInstance; - public static WebMediumConfig instance; - public static ForumPostConfig post; - public static IssueConfig issue; - public static UserConfig user; - public static UserConfig viewUser; - public static String type = "Bots"; - public static BotModeConfig botMode = new BotModeConfig(); - public static VoiceConfig voice = new VoiceConfig(); - public static LearningConfig learning = new LearningConfig(); - public static AvatarMedia avatarMedia; - public static ResponseConfig response; - public static ScriptSourceConfig script; - public static String conversation; - public static String template = ""; - public static String currentPhotoPath; - public static List templates; - public static Object[] tags; - public static Object[] categories; - public static Object[] forumTags; - public static Object[] forumPostTags; - public static Object[] forumCategories; - public static Object[] channelTags; - public static Object[] channelCategories; - public static Object[] avatarTags; - public static Object[] scriptTags; - public static Object[] scriptCategories; - public static Object[] avatarCategories; - public static int volume; - - public static String contentRating; - public static Object[] domainTags; - public static Object[] domainCategories; - - public static String nameOfAvatar; - - public static Object[] graphicTags; - public static Object[] graphicCategories; - public static boolean showImages = true; - public static BrowseConfig browse = null; - public static BrowseConfig browsePosts = null; - public static BrowseConfig browseIssues = null; - public static List instances = new ArrayList(); - public static List posts = new ArrayList(); - public static List issues = new ArrayList(); - public static List avatarMedias = new ArrayList(); - public static MainAbility current; - public static boolean browsing; - public static boolean searching; - public static boolean searchingPosts; - public static boolean searchingIssues; - public static boolean wasDelete; - public static boolean importingBotScript = false; - public static boolean importingBotLog = false; - public static String[] languages = new String[]{ - "Default", - "af - Afrikaans", "sq - Albanian", "ar - Arabic", "hy - Armenian", "az - Azerbaijani", - "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - Bulgarian", - "ca - Catalan", "zh - Chinese", "hr - Croatian", "cs - Czech", "da - Danish", "nl - Dutch", "en - English", "et - Estonian", "fi - Finnish", "fr - French", - "gl - Galician", "ka - Georgian", "de - German", "el - Greek", "gu - Gujarati", "ht - Haitian", "he - Hebrew", "hi - Hindi", "hu - Hungarian", - "is - Icelandic", "id - Indonesian", "ga - Irish", "it - Italian", "ja - Japanese", "kn - Kannada", "kk - Kazakh", "ky - Kirghiz", "ko - Korean", - "la - Latin", "lv - Latvian", "lt - Lithuanian", "mk - Macedonian", "mg - Malagasy", "ms - Malay", "mt - Maltese", "mn - Mongolian", "no - Norwegian", - "fa - Persian", "pl - Polish", "pt - Portuguese", "pa - Punjabi", "ro - Romanian", "ru - Russian", - "sr - Serbian", "si - Sinhalese", "sk - Slovak", "sl - Slovenian", "es - Spanish", "sw - Swahili", "sv - Swedish", - "tl - Tagalog", "tg - Tajik", "ta - Tamil", "tt - Tatar", "th - Thai", "tr - Turkish", - "udm - Udmurt", "uk - Ukrainian", "ur - Urdu", "uz - Uzbek", "vi - Vietnamese", "cy - Welsh" - }; - public static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; - public static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; - public static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - public static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; - public static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - public static String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; - public static String[] forkAccMode = new String[]{"Administrators", "Members", "Users", "Disabled"}; - public static String[] mediaAccessModes = new String[]{"Administrators", "Everyone", "Members", "Users", "Disabled"}; - public static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] scriptLanguages = new String[]{"Self", "AIML", "Response List", "Chat Log", "CVS"}; - public static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - public static String[] responseTypes = new String[]{"conversations", "responses", "greetings", "default", "flagged"}; - public static String[] durations = new String[]{"all", "day", "week", "month"}; - public static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; - public static String[] responseRestrictions = new String[]{"", "exact", "keyword", "required", "topic", "label", "previous", - "repeat", "missing-keyword", "missing-required", "missing-topic", "patterns", "templates", "flagged", "corrections", - "emotions", "actions", "poses"}; - public static String[] voices = new String[]{ - "cmu-slt", - "cmu-slt-hsmm", - "cmu-bdl-hsmm", - "cmu-rms-hsmm", - "dfki-prudence", - "dfki-prudence-hsmm", - "dfki-spike", - "dfki-spike-hsmm", - "dfki-obadiah", - "dfki-obadiah-hsmm", - "dfki-poppy", - "dfki-poppy-hsmm", - "bits1-hsmm", - "bits3", - "bits3-hsmm", - "dfki-pavoque-neutral-hsmm", - "camille", - "camille-hsmm-hsmm", - "jessica_voice-hsmm", - "pierre-voice-hsmm", - "enst-dennys-hsmm", - "istc-lucia-hsmm", - "voxforge-ru-nsh", - "dfki-ot", - "dfki-ot-hsmm", - "cmu-nk", - "cmu-nk-hsmm" - }; - public static String[] voiceMods = new String[]{ - "default", "child", "whisper", "echo", "robot" - }; - public static String[] voiceNames = new String[]{ - "English : US : Female : SLT", - "English : US : Female : SLT (hsmm)", - "English : US : Male : BDL (hsmm)", - "English : US : Male : RMS (hsmm)", - "English : GB : Female : Prudence", - "English : GB : Female : Prudence (hsmm)", - "English : GB : Male : Spike", - "English : GB : Male : Spike (hsmm)", - "English : GB : Male : Obadiah", - "English : GB : Male : Obadiah (hsmm)", - "English : GB : Female : Poppy", - "English : GB : Female : Poppy (hsmm)", - "German : DE : Female : Bits1 (hsmm)", - "German : DE : Male : Bits3", - "German : DE : Male : Bits3 (hsmm)", - "German : DE : Male : Pavoque (hsmm)", - "French : FR : Female : Camille", - "French : FR : Female : Camille (hsmm)", - "French : FR : Female : Jessica (hsmm)", - "French : FR : Male : Pierre (hsmm)", - "French : FR : Male : Dennys (hsmm)", - "Italian : IT : Male : Lucia (hsmm)", - "Russian : RU : Male : NSH (hsmm)", - "Turkish : TR : Male : OT", - "Turkish : TR : Male : OT (hsmm)", - "Telugu : TE : Female : NK", - "Telugu : TE : Female : NK (hsmm)" - }; + /** + * setHandsFreeSpeech + * + * @param handsFreeSpeech + */ + public static void setHandsFreeSpeech(boolean handsFreeSpeech) { + MainAbility.handsFreeSpeech = handsFreeSpeech; + } - Menu menu; - public static int templateID; - public Button spin; - public Button createInstanceButton; - public Button browseButton; - public Button menuButton; - public Button loginButton; - public Button chatButton; - public Button logoutButton; - public Button viewUserButton; - public Button helpButton; - -// // @TargetApi(Build.VERSION_CODES.KITKAT) -//// @SuppressLint("NewApi") -// public static String getFilePathFromURI(Context context, Uri uri) { -// // DocumentProvider -// if (DocumentsContract.isDocumentUri(context, uri)) { -// -// // ExternalStorageProvider -// if (isExternalStorageDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// -// if ("primary".equalsIgnoreCase(type)) { -// return Environment.getExternalStorageDirectory() + "/" + split[1]; -// } -// // TODO handle non-primary volumes -// } -// // DownloadsProvider -// else if (isDownloadsDocument(uri)) { -// final String id = DocumentsContract.getDocumentId(uri); -// final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), -// Long.valueOf(id)); -// return getDataColumn(context, contentUri, null, null); -// } -// // MediaProvider -// else if (isMediaDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// Uri contentUri = null; -// if ("image".equals(type)) { -// contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; -// } else if ("video".equals(type)) { -// contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; -// -// } else if ("audio".equals(type)) { -// contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; -// } -// final String selection = "_id=?"; -// final String[] selectionArgs = new String[]{split[1]}; -// return getDataColumn(context, contentUri, selection, selectionArgs); -// } -// } -// // MediaStore (and general) -// else if ("content".equalsIgnoreCase(uri.getScheme())) { -// // Return the remote address -// if (isGooglePhotosUri(uri)) -// return uri.getLastPathSegment(); -// return getDataColumn(context, uri, null, null); -// } -// // File -// else if ("file".equalsIgnoreCase(uri.getScheme())) { -// return uri.getPath(); -// } -// return null; -// } - - public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { -// Cursor cursor = null; -// final String column = "_data"; -// final String[] projection = {column}; -// try { -// cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); -// if (cursor != null && cursor.moveToFirst()) { -// final int index = cursor.getColumnIndexOrThrow(column); -// return cursor.getString(index); -// } -// } finally { -// if (cursor != null) -// cursor.close(); -// } - return null; + /** + * isOnline + * + * @return dd + */ + public static boolean isOnline() { + return online; } + /** + * getFileSize + * + * @param q + * @param a + * @return dd + */ public static Boolean getFileSize(String q, Context a) { if (q == null || q.equals("")) { return true; @@ -441,80 +916,33 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } - public static boolean isExternalStorageDocument(Uri uri) { - return "com.ohos.externalstorage.documents".equals(uri.getDecodedAuthority()); - } - /** - * Whether the Uri authority is DownloadsProvider. + * isTablet * - * @param uri uri - * @return Whether the Uri authority is DownloadsProvider. + * @param context + * @return dd */ - public static boolean isDownloadsDocument(Uri uri) { - return "com.ohos.providers.downloads.documents".equals(uri.getDecodedAuthority()); + public static boolean isTablet(Context context) { + return true; } /** - * Whether the Uri authority is MediaProvider. + * getAbility * - * @param uri uri - * @return Whether the Uri authority is MediaProvider. + * @param config + * @return dd */ - public static boolean isMediaDocument(Uri uri) { - return "com.ohos.providers.media.documents".equals(uri.getDecodedAuthority()); + public static Class getAbility(WebMediumConfig config) { + return null; } /** - * Whether the Uri authority is Google Photos. + * error * - * @param uri uri - * @return Whether the Uri authority is Google Photos. + * @param message + * @param exception + * @param ability */ - public static boolean isGooglePhotosUri(Uri uri) { - return "com.google.ohos.apps.photos.content".equals(uri.getDecodedAuthority()); - } - - public static String getFileNameFromPath(String path) { - int index = path.lastIndexOf("/"); - return path.substring(index + 1, path.length()); - } - -// public static String getFileTypeFromPath(String path) { -// int index = path.lastIndexOf("."); -// String ext = path.substring(index + 1, path.length()); -// if (ext.equalsIgnoreCase("webm")) { -// return "video/webm"; -// } -// return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); -// } - - public static boolean isTablet(Context context) { -// return (context.getResourceManager().getConfiguration().isLayoutRTL -// & Configuration.AUTO_MODE) >= Configuration.AUTO_MODE; - return true; - } - - @SuppressWarnings("rawtypes") - public static Class getAbility(WebMediumConfig config) { - if (config instanceof ChannelConfig) { -// return ChannelAbility.class; //==================== - } else if (config instanceof ForumConfig) { -// return ForumAbility.class; //==================== - } else if (config instanceof InstanceConfig) { -// return BotAbility.class; //==================== - } else if (config instanceof DomainConfig) { -// return DomainAbility.class; //==================== - } else if (config instanceof AvatarConfig) { -// return AvatarAbility.class; //==================== - } else if (config instanceof ScriptConfig) { -// return ScriptAbility.class; //==================== - } else if (config instanceof GraphicConfig) { -// return GraphicAbility.class; //==================== - } - return null; - } - public static void error(String message, Exception exception, Ability ability) { try { if (DEBUG) { @@ -535,6 +963,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * errorInfo + * + * @param type + * @param message + * @param exception + * @param ability + */ public static void errorInfo(int type, String message, Exception exception, Ability ability) { try { if (DEBUG) { @@ -555,6 +991,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * showMessage + * + * @param title + * @param message + * @param ability + */ public static void showMessage(String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -583,6 +1026,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * showLogin + * + * @param title + * @param message + * @param ability + */ public void showLogin(String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -612,8 +1062,16 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } - public static Text execcontentinfo; + private static Text execcontentinfo; + /** + * showMessageInfo + * + * @param type + * @param title + * @param message + * @param ability + */ public static void showMessageInfo(int type, String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -651,64 +1109,19 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * showMessage + * + * @param message + * @param ability + */ public static void showMessage(String message, Ability ability) { showMessage(null, message, ability); } - public static void prompt(String message, Ability ability, TextField text, IDialog.ClickedListener listener) { - CommonDialog dialog = new CommonDialog(ability); - dialog.setContentText(message); - dialog.setContentCustomComponent(text); - dialog.setButton(0, "OK", listener); - dialog.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - - } - }); - dialog.show(); - } - - public void contentRatingList() { - CommonDialog builder = new CommonDialog(this); - builder.setTitleText("Content Rating"); - - builder.setContentText("Select Content Rating: "); - builder.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int id) { - // save data -// Preferences editor = MainAbility.current.getp.getPreferences(Context.MODE_PRIVATE) -// .edit(); -// editor.putString("contentRating", (String) spin.getSelectedItem()); -// contentRating = (String) spin.getSelectedItem(); -// editor.flush(); - } - }); - - builder.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - - } - }); - builder.show(); - } - - public static void confirm(String message, Ability ability, Boolean cancelable, IDialog.ClickedListener listener) { - CommonDialog dialog = new CommonDialog(ability); - dialog.setTitleText("Pizza Bot"); - dialog.setContentText(message); - dialog.setButton(0, "Yes", listener); - dialog.setButton(1, "NO", listener); - if (cancelable) { - dialog.setButton(1, "Cancel", listener); - } - dialog.show(); - } - - - + /** + * REQ_PERMISSION_CODE + */ public static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( @@ -718,12 +1131,11 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag @Override public void onStart(Intent intent) { super.onStart(intent); -// super.setMainRoute(MainAbilitySlice.class.getName()); - searching = false; - browsing = false; - searchingPosts = false; - importingBotLog = false; - importingBotScript = false; + setSearching(false); + setBrowsing(false); + setSearchingPosts(false); + setImportingBotLog(false); + setImportingBotScript(false); if (user != null) { Preferences cookies = PreferencesUtils.getPreferences(this); cookies.putString("user", MainAbility.user.user); @@ -731,27 +1143,18 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag cookies.flushSync(); } - current = this; + setCurrent(this); Preferences cookies = PreferencesUtils.getPreferences(this); // saved handsFreeSpeech toggle - load cookies. - handsFreeSpeech = cookies.getBoolean("handsfreespeech", handsFreeSpeech); - listenInBackground = cookies.getBoolean("listenInBackground", listenInBackground); - offlineSpeech = cookies.getBoolean("offlineSpeech", offlineSpeech); -// ChatAbility.DEBUG = cookies.getBoolean("debug", ChatAbility.DEBUG); //=============================================== - launchInstanceId = cookies.getString("instanceID", launchInstanceId); - launchInstanceName = cookies.getString("instanceName", launchInstanceName); - // saving the a number of array as an ID, for the sake of loading the - // exact saved bot. - templateID = cookies.getInt("tempId", templateID); - nameOfAvatar = cookies.getString("nameOfAvatar", nameOfAvatar); - System.out.println("Name of avatar: " + nameOfAvatar); - // load memory: by bot's name - + setHandsFreeSpeech(cookies.getBoolean("handsfreespeech", handsFreeSpeech)); + setListenInBackground(cookies.getBoolean("listenInBackground", listenInBackground)); + setOfflineSpeech(cookies.getBoolean("offlineSpeech", offlineSpeech)); + setLaunchInstanceId(cookies.getString("instanceID", launchInstanceId)); + setLaunchInstanceName(cookies.getString("instanceName", launchInstanceName)); + setTemplateID(cookies.getInt("tempId", templateID)); + setNameOfAvatar(cookies.getString("nameOfAvatar", nameOfAvatar)); loadMemoryByBot(); - - // Checking and making sure that the mic is turned off to start - // configuring the microphone. - micConfig = cookies.getBoolean("miconfig", micConfig); + setMicConfig(cookies.getBoolean("miconfig", micConfig)); if (user == null) { String user = cookies.getString("user", null); @@ -773,30 +1176,28 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag UserConfig config = new UserConfig(); config.user = user; config.token = token; - HttpConnectAction action = new HttpConnectAction(this, config, false); -// action.execute(); } - String voice = cookies.getString("voice", null); + String voice = cookies.getString("voice", ""); String language = cookies.getString("language", null); String translate = cookies.getString("translate", null); String nativeVoice = cookies.getString("nativeVoice", null); if (voice != null) { - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); - MainAbility.voice.voice = voice; - MainAbility.voice.language = language; - MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setCustomVoice(true); + setVoice(new VoiceConfig()); + getVoice().voice = voice; + getVoice().language = language; + getVoice().nativeVoice = Boolean.valueOf(nativeVoice); + setDeviceVoice(getVoice().nativeVoice); } if (translate != null) { - MainAbility.translate = true; - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); - MainAbility.voice.language = language; - MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setTranslate(true); + setCustomVoice(true); + setVoice(new VoiceConfig()); + getVoice().language = language; + getVoice().nativeVoice = Boolean.valueOf(nativeVoice); + setDeviceVoice(MainAbility.voice.nativeVoice); } } @@ -812,10 +1213,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } resetView(); - searching = false; - hd = isTablet(this); + setSearching(false); + setHd(isTablet(this)); } + /** + * initChat + */ public void initChat() { chatButton = (Button) findComponentById(ResourceTable.Id_chatButton); // chat chatButton.setClickedListener(new Component.ClickedListener() { @@ -826,6 +1230,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * initMain + */ public void initMain() { spin = (Button) findComponentById(ResourceTable.Id_selectButton); // 底部类型选择 spin.setClickedListener(new Component.ClickedListener() { @@ -887,6 +1294,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * initBrowse + */ public void initBrowse() { chatButton = (Button) findComponentById(ResourceTable.Id_chatButton); chatButton.setClickedListener(new Component.ClickedListener() { @@ -957,20 +1367,22 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * loadMemoryByBot + */ public void loadMemoryByBot() { - MicroMemory.storageDir = getFilesDir(); - List items = new ArrayList(); - items = ListTemplateView.retriveTemplates(); + List items = ListTemplateView.retriveTemplates(); OfflineTemplateConfig oneItem; oneItem = items.get(templateID); System.out.println("StorageFileName :" + oneItem.getTitle()); - offlineSelectedImage = oneItem.getImageId(); - MicroMemory.storageFileName = oneItem.getTitle(); - launchInstanceName = oneItem.getTitle(); - launchInstanceId = oneItem.getId(); + setOfflineSelectedImage(oneItem.getImageId()); + setLaunchInstanceName(oneItem.getTitle()); + setLaunchInstanceId(oneItem.getId()); } - @SuppressWarnings({"unchecked", "rawtypes"}) + /** + * resetView + */ public void resetView() { menuButton = (Button) findComponentById(ResourceTable.Id_menuButton); // 菜单选择 menuButton.setClickedListener(new Component.ClickedListener() { @@ -995,14 +1407,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag resetLast(); } + /** + * resetLast + */ public void resetLast() { if (type.equals("Chat Bot Wars")) { war(); return; } - if (type == null) { - type = MainAbility.defaultType; - } Button button = (Button) findComponentById(ResourceTable.Id_lastButton); if (button != null) { Preferences cookies = PreferencesUtils.getPreferences(this); @@ -1033,60 +1445,11 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } - public void openLast() { - -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); // 适配器中做了选择赋值 -// if (spin != null) { -// type = (String) spin.getSelectedItem(); -// } - if (type == null) { - type = MainAbility.defaultType; - } - Preferences cookies = PreferencesUtils.getPreferences(this); - String last = null; - if (type.equals("Forums")) { - last = cookies.getString("forum", null); - } else if (type.equals("Live Chat")) { - last = cookies.getString("channel", null); - } else if (type.equals("Domains")) { - last = cookies.getString("domain", null); - } else if (type.equals("Avatars")) { - last = cookies.getString("avatar", null); - } else if (type.equals("Scripts")) { - last = cookies.getString("script", null); - } else if (type.equals("Graphics")) { - last = cookies.getString("graphic", null); - } else { - last = cookies.getString("instance", null); - } - - if (last == null) { - MainAbility.showMessage("Invalid cookie", this); - return; - } - - WebMediumConfig config = null; - if (type.equals("Forums")) { - config = new ForumConfig(); - } else if (type.equals("Live Chat")) { - config = new ChannelConfig(); - } else if (type.equals("Domains")) { - config = new DomainConfig(); - } else if (type.equals("Avatars")) { - config = new AvatarConfig(); - } else if (type.equals("Scripts")) { - config = new ScriptConfig(); - } else if (type.equals("Graphics")) { - config = new GraphicConfig(); - } else { - config = new InstanceConfig(); - } - config.name = last; - - HttpFetchAction action = new HttpFetchAction(this, config); -// action.execute(); - } - + /** + * resetMenu + * + * @param menu + */ public void resetMenu(Menu menu) { if (menu == null) { return; @@ -1094,79 +1457,42 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag for (int index = 0; index < menu.getItemCount(); index++) { menu.getItem(index).setEnabled(true); } - if (MainAbility.user == null) { - //menu.findItem(R.id.menuMyBots).setEnabled(false); - //menu.findItem(R.id.menuSignOut).setEnabled(false); - //menu.findItem(R.id.menuViewUser).setEnabled(false); - //menu.findItem(R.id.menuEditUser).setEnabled(false); - } else { - //menu.findItem(R.id.menuSignIn).setEnabled(false); - //menu.findItem(R.id.menuSignUp).setEnabled(false); - } - - /*if (MicroMemory.checkExists()) { - menu.findItem(R.id.menuDeleteExistingBot).setEnabled(true); - } else { - menu.findItem(R.id.menuDeleteExistingBot).setEnabled(false); - }*/ -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String) spin.getSelectedItem(); -// } if (type == null) { type = MainAbility.defaultType; } - // MenuItem item = menu.findItem(R.id.menuMyBots); - // if (type.equals("Bots")) { - // item.setTitle("My Bots"); - // } else if (type.equals("Forums")) { - // item.setTitle("My Forums"); - // } else if (type.equals("Live Chat")) { - // item.setTitle("My Channels"); - // } else if (type.equals("Domains")) { - // item.setTitle("My Domains"); - // } else if (type.equals("Avatars")) { - // item.setTitle("My Avatars"); - // } else if (type.equals("Scripts")){ - // item.setTitle("My Scripts"); - // }else if (type.equals("Graphics")){ - // item.setTitle("My Graphics"); - // } } + /** + * war + */ public void war() { startOpenAbility(this, StartWarAbility.class.getName()); } + /** + * login + */ public void login() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } - startOpenAbility(this, LoginAbility.class.getName()); } + /** + * logout + */ public void logout() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } connection.disconnect(); - user = null; - instance = null; - conversation = null; - post = null; - posts = new ArrayList(); - instances = new ArrayList(); - domain = null; - tags = null; - categories = null; - learning = null; - voice = null; - customVoice = false; - translate = false; + setUser(null); + setInstance(null); + setConversation(null); + setPost(null); + setPosts(new ArrayList()); + setInstances(new ArrayList()); + setDomain(null); + setLearning(null); + setVoice(null); + setCustomVoice(false); + setTranslate(false); Preferences editor = PreferencesUtils.getPreferences(this); editor.delete("user"); @@ -1193,6 +1519,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag startAbility(intent); } + /** + * menu + */ public void menu() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); @@ -1247,7 +1576,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag editprofile.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - editUser(); } }); statistics.setClickedListener(new Component.ClickedListener() { @@ -1261,7 +1589,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag changelanguage.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - changeLanguage(MainAbility.this, null); + changeLanguage(); menuDialog.destroy(); } }); @@ -1296,13 +1624,18 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * createUser + */ public void createUser() { startOpenAbility(this, CreateUserAbility.class.getName()); } - public void editUser() { - } - + /** + * setOnline + * + * @param result + */ public static void setOnline(boolean result) { if (result) { connection = remoteConnection; @@ -1312,14 +1645,23 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag online = result; } + /** + * help + */ public void help() { startOpenAbility(this, HelpAbility.class.getName()); } + /** + * viewUser + */ public void viewUser() { - viewUser = user; + setViewUser(user); } + /** + * openWebsite + */ public void openWebsite() { try { Intent intent2 = new Intent(); @@ -1333,23 +1675,25 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * createInstance + */ public void createInstance() { if (user == null) { showLogin("", "You must sign in first", this); return; } -// Spinner spin = (Spinner) findViewById(getResources().getIdentifier("typeSpin", "id", getPackageName())); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } if (type == null) { type = MainAbility.defaultType; } if (type.equals("Bots")) { - MainAbility.template = ""; + setTemplate(""); } } + /** + * search + */ public void search() { if (type == null) { type = MainAbility.defaultType; @@ -1373,34 +1717,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } - public void browseMyBots() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } - if (type == null) { - type = MainAbility.defaultType; - } - BrowseConfig config = new BrowseConfig(); - config.typeFilter = "Personal"; - if (type.equals("Bots")) { - config.type = "Bot"; - } else if (type.equals("Forums")) { - config.type = "Forum"; - } else if (type.equals("Live Chat")) { - config.type = "Channel"; - } else if (type.equals("Domains")) { - config.type = "Domain"; - } else if (type.equals("Avatars")) { - config.type = "Avatar"; - } else if (type.equals("Scripts")) { - config.type = "Script"; - } else if (type.equals("Graphics")) { - config.type = "Graphic"; - } - config.contentRating = "Mature"; - } - + /** + * browse + */ public void browse() { if (type == null) { type = MainAbility.defaultType; @@ -1417,13 +1736,12 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } else if (type.equals("Avatars")) { config.type = "Avatar"; } else if (type.equals("Scripts")) { - importingBotScript = false; + setImportingBotScript(false); config.type = "Script"; } else if (type.equals("Graphics")) { config.type = "Graphic"; } config.contentRating = MainAbility.contentRating; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); } /** @@ -1440,20 +1758,11 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } config.id = launchInstanceId; config.name = launchInstanceName; - - HttpFetchAction action = new HttpFetchAction(this, config, false); -// action.execute(); } /** * Start a chat session with the hard coded instance. */ - - /* - * This method will have a list of 8 empty bot, basic, AI, julie, eddie, - * alice, personal assistance, juile assistance. before attaching the ID and - * Name of the bot make sure that its selecetd thro the list. - */ public void launch() { setOnline(false); WebMediumConfig config = null; @@ -1463,92 +1772,38 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag config = new InstanceConfig(); OfflineTemplateConfig templates = new OfflineTemplateConfig(ResourceTable.Media_bot, "Pizza Bot", "", "" + 0, 0); - //saving a template number for getting the icons and pictures of the bot - saveAllData(MainAbility.launchInstanceName = templates.getTitle(), MainAbility.launchInstanceId = templates.getId(), MainAbility.templateID = 0); config.id = MainAbility.launchInstanceId; config.name = MainAbility.launchInstanceName; AvatarSelection.saveSelectedAvatar(templates.getTitle()); - MainAbility.readZipAvatars(this, templates.getTitle()); - MainAbility.offlineSelectedImage = templates.getImageId(); + setOfflineSelectedImage(templates.getImageId()); HttpAction action = new HttpFetchActionOffline(this, config, true); action.execute(); } else { config = new InstanceConfig(); - readZipAvatars(this, this.nameOfAvatar); config.name = MainAbility.launchInstanceName; config.id = MainAbility.launchInstanceId; HttpAction action = new HttpFetchActionOffline(this, config, true); action.execute(); } - } else if (MainAbility.launchType == LaunchType.Forum) { - config = new ForumConfig(); - } else if (MainAbility.launchType == LaunchType.Channel) { - config = new ChannelConfig(); } } - public void saveAllData(String instanceId, String instanceName, int id) { -// Preferences cookies = MainAbility.current.getPreferences(Context.MODE_PRIVATE).edit(); - Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putString("instanceID", instanceId); - cookies.putString("instanceName", instanceName); - cookies.putInt("tempId", id); - cookies.flushSync(); - } - - /** - * View the user's personal instance. - */ - public void browseMyBot() { - if (user == null) { - CommonDialog dialog = new CommonDialog(this); - dialog.setContentText("You must sign in first"); - dialog.setButton(1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - login(); - } - }); - dialog.show(); - return; - } - WebMediumConfig config = new InstanceConfig(); - config.name = "Bot " + MainAbility.user.user; + private static String selectInfo = ""; - HttpFetchOrCreateAction action = new HttpFetchOrCreateAction(this, config, false); -// action.execute(); + public static String getSelectInfo() { + return selectInfo; } - /** - * Start a chat session with the user's personal instance. - * - * @param view view - */ - public void launchMyBot(View view) { - if (user == null) { - CommonDialog dialog = new CommonDialog(this); - dialog.setContentText("You must sign in first"); - dialog.setButton(1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - login(); - } - }); - dialog.show(); - return; - } - WebMediumConfig config = new InstanceConfig(); - config.name = "Bot " + MainAbility.user.user; - - HttpFetchOrCreateAction action = new HttpFetchOrCreateAction(this, config, true); -// action.execute(); + public static void setSelectInfo(String selectInfo) { + MainAbility.selectInfo = selectInfo; } - public static String selectInfo = ""; Text languageselect; - @SuppressWarnings({"rawtypes", "unchecked"}) - public void changeLanguage(Ability activty, final IDialog.ClickedListener listener) { + /** + * changeLanguage + */ + public void changeLanguage() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -1558,9 +1813,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag CommonDialog dialog = new CommonDialog(MainAbility.this); setOnline(true); -// dialog.setTitleText(" Languages"); dialog.setSize(displayAttributes.width - 100, displayAttributes.width - 300); -// dialog.setContentText("Select your language"); dialog.setContentCustomComponent(layout); dialog.show(); @@ -1576,31 +1829,20 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } }); - int index = -1; - - if (MainAbility.voice != null && MainAbility.voice.language != null) { - index = Arrays.asList(MainAbility.languages).indexOf(MainAbility.voice.language); - } -// spin.setSelection(index); if (MainAbility.voice.language == null || MainAbility.voice.language.isEmpty()) { languageselect.setText(MainAbility.languages[0] + ""); } else { languageselect.setText(MainAbility.voice.language + ""); } - if (MainAbility.voice != null && MainAbility.voice.language != null) { - for (int i = 0; i < spinnerAdapter.getCount(); i++) { - if (MainAbility.languages[i].contains(MainAbility.voice.language + " - ")) { -// spin.setSelection(i); - selectInfo = MainAbility.languages[i]; - } + for (int i = 0; i < spinnerAdapter.getCount(); i++) { + if (MainAbility.languages[i].contains(MainAbility.voice.language + " - ")) { + setSelectInfo(MainAbility.languages[i]); } } -// dialog.setView(spin); ok.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - // String lang = (String)spin.getSelectedItem(); String lang = MainAbility.selectInfo; if (lang.equals("Default")) { MainAbility.translate = false; @@ -1645,11 +1887,4 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } }); } - - public static void readZipAvatars(Ability ability, String fileName) { - String args[] = fileName.split("\\s+"); - try { - } catch (Exception ignore) { - } - } } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/PaphusCredentials.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/PaphusCredentials.java deleted file mode 100644 index f895330e85d994cd02f5c2330396fbd149fa6c8f..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/PaphusCredentials.java +++ /dev/null @@ -1,39 +0,0 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -package org.botlibre.sdk; - -/** - * Credentials for use with hosted services on the Bot Libre for Business website, - * a commercial bot, live chat, chatroom, and forum hosting service. - * https://www.botlibre.biz - */ -public class PaphusCredentials extends Credentials { - public static String DOMAIN = "www.botlibre.biz"; - //public static String DOMAIN = "192.168.0.11:9080"; - public static String APP = ""; - //public static String APP = "/livechat"; - public static String PATH = "/rest/api"; - - public PaphusCredentials(String applicationId) { - this.host = DOMAIN; - this.app = APP; - this.url = "https://" + DOMAIN + APP + PATH; - this.applicationId = applicationId; - } -} \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/SDKConnection.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/SDKConnection.java index fe1ac75f7e81a2765c563c747cdf003c45a3b5b6..39bdafc1607ac8b71d4e06b079b955c15fc1962a 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/SDKConnection.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/SDKConnection.java @@ -18,49 +18,12 @@ package org.botlibre.sdk; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; import com.franmontiel.persistentcookiejar.ClearableCookieJar; import com.franmontiel.persistentcookiejar.PersistentCookieJar; import com.franmontiel.persistentcookiejar.cache.SetCookieCache; import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor; -import ohos.agp.components.element.ShapeElement; -import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.AvatarMedia; -import org.botlibre.sdk.config.AvatarMessage; -import org.botlibre.sdk.config.BotModeConfig; -import org.botlibre.sdk.config.BrowseConfig; -import org.botlibre.sdk.config.ChannelConfig; -import org.botlibre.sdk.config.ChatConfig; -import org.botlibre.sdk.config.ChatResponse; -import org.botlibre.sdk.config.Config; -import org.botlibre.sdk.config.ContentConfig; -import org.botlibre.sdk.config.ConversationConfig; -import org.botlibre.sdk.config.DomainConfig; -import org.botlibre.sdk.config.ForumConfig; -import org.botlibre.sdk.config.ForumPostConfig; -import org.botlibre.sdk.config.GraphicConfig; -import org.botlibre.sdk.config.InstanceConfig; -import org.botlibre.sdk.config.IssueConfig; -import org.botlibre.sdk.config.LearningConfig; -import org.botlibre.sdk.config.MediaConfig; -import org.botlibre.sdk.config.ResponseConfig; -import org.botlibre.sdk.config.ResponseSearchConfig; -import org.botlibre.sdk.config.ScriptConfig; -import org.botlibre.sdk.config.ScriptSourceConfig; -import org.botlibre.sdk.config.Speech; -import org.botlibre.sdk.config.UserAdminConfig; -import org.botlibre.sdk.config.UserConfig; -import org.botlibre.sdk.config.UserMessageConfig; -import org.botlibre.sdk.config.VoiceConfig; -import org.botlibre.sdk.config.WebMediumConfig; import ohos.aafwk.ability.Ability; -import ohos.media.image.PixelMap; +import ohos.agp.components.element.ShapeElement; import okhttp3.Call; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -73,17 +36,35 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntity; -import org.apache.http.entity.mime.content.ByteArrayBody; -import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; +import org.botlibre.sdk.config.AvatarConfig; +import org.botlibre.sdk.config.AvatarMedia; +import org.botlibre.sdk.config.BrowseConfig; +import org.botlibre.sdk.config.ChannelConfig; +import org.botlibre.sdk.config.ChatConfig; +import org.botlibre.sdk.config.ChatResponse; +import org.botlibre.sdk.config.Config; +import org.botlibre.sdk.config.DomainConfig; +import org.botlibre.sdk.config.ForumConfig; +import org.botlibre.sdk.config.ForumPostConfig; +import org.botlibre.sdk.config.GraphicConfig; +import org.botlibre.sdk.config.InstanceConfig; +import org.botlibre.sdk.config.IssueConfig; +import org.botlibre.sdk.config.ResponseConfig; +import org.botlibre.sdk.config.ScriptConfig; +import org.botlibre.sdk.config.UserConfig; +import org.botlibre.sdk.config.WebMediumConfig; import org.w3c.dom.Element; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + /** * Connection class for a REST service connection. * The SDK connection gives you access to the paphus or libre server services using a REST API. @@ -98,15 +79,10 @@ import org.w3c.dom.Element; * */ public class SDKConnection { - protected static String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; - protected static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - protected static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - protected static String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; - protected static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - protected static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; - + private static final String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; + private static final String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; + private static final String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; + protected String url; protected UserConfig user; protected DomainConfig domain; @@ -141,10 +117,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-user", config.toXML()); Element root = parse(xml); - if (root == null) { - this.user = null; - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -168,9 +140,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/" + api, config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { result.parseXML(root); } catch (Exception exception) { @@ -209,9 +178,7 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/view-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } + try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -237,52 +204,6 @@ public class SDKConnection { } } - /** - * Fetch the forum post details for the forum post id. - * - * @param config config - * @return Fetch the forum post details for the forum post id. - */ - public ForumPostConfig fetch(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-forum-post", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ForumPostConfig post = new ForumPostConfig(); - post.parseXML(root); - return post; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Fetch the issue details for the issue id. - * - * @param config config - * @return Fetch the issue details for the issue id. - */ - public IssueConfig fetch(IssueConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-issue", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - IssueConfig issue = new IssueConfig(); - issue.parseXML(root); - return issue; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Create a new user. * @@ -294,9 +215,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POSTUpdate(ability,this.url + "/create-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -318,9 +236,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-forum-post", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ForumPostConfig post = new ForumPostConfig(); post.parseXML(root); @@ -341,9 +256,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-issue", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { IssueConfig issue = new IssueConfig(); issue.parseXML(root); @@ -354,159 +266,6 @@ public class SDKConnection { } } - /** - * Create a new file/image/media attachment for a chat channel. - * - * @param file file - * @param config config - * @return Create a new file/image/media attachment for a chat channel. - */ - public MediaConfig createChannelFileAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTFILE(this.url + "/create-channel-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for a chat channel. - * - * @param file file - * @param config config - * @return Create a new image attachment for a chat channel. - */ - public MediaConfig createChannelImageAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-channel-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new file/image/media attachment for an issue tracker. - * - * @param file file - * @param config config - * @return Create a new file/image/media attachment for an issue tracker. - */ - public MediaConfig createIssueTrackerFileAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTFILE(this.url + "/create-issuetracker-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for an issue tracker. - * - * @param file file - * @param config config - * @return Create a new image attachment for an issue tracker. - */ - public MediaConfig createIssueTrackerImageAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-issuetracker-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for an issue tracker. - * - * @param bitmap bitmap - * @param config config - * @return Create a new image attachment for an issue tracker. - */ - public MediaConfig createIssueTrackerImageAttachment(PixelMap bitmap, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-issuetracker-attachment", bitmap, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a reply to a forum post. - * - * @param config config - * @return Create a reply to a forum post. - */ - public ForumPostConfig createReply(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/create-reply", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ForumPostConfig reply = new ForumPostConfig(); - reply.parseXML(root); - return reply; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a user message. - * - * @param config config - */ - public void createUserMessage(UserMessageConfig config) { - config.addCredentials(this); - POST(this.url + "/create-user-message", config.toXML()); - } - /** * Fetch the content details from the server. * @@ -519,9 +278,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T)config.getClass().newInstance(); config.parseXML(root); @@ -545,9 +301,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T)config.getClass().newInstance(); config.parseXML(root); @@ -570,9 +323,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/update-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T)config.getClass().newInstance(); config.parseXML(root); @@ -582,100 +332,6 @@ public class SDKConnection { throw this.exception; } } - - /** - * Update the forum post. - * - * @param config config - * @return Update the forum post. - */ - public ForumPostConfig update(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-forum-post", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new ForumPostConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the issue. - * - * @param config config - * @return Update the issue. - */ - public IssueConfig update(IssueConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-issue", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new IssueConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create or update the response. - * - * @param config config - * @return Create or update the response. - */ - public ResponseConfig saveResponse(ResponseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/save-response", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ResponseConfig response = new ResponseConfig(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the user details. - * - * @param config config - * @return Update the user details. - */ - public UserConfig update(UserConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-user", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - UserConfig user = new UserConfig(); - user.parseXML(root); - this.user = user; - return user; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Permanently delete the content with the id. * @@ -949,9 +605,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/post-chat", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ChatResponse response = new ChatResponse(); response.parseXML(root); @@ -961,104 +614,18 @@ public class SDKConnection { throw this.exception; } } - + /** - * Process the avatar message and return the avatars response. - * This allows the speech and video animation for an avatar to be generated for the message. + * Return the list of forum posts for the forum browse criteria. * * @param config config - * @return avatarMessage + * @return Return the list of forum posts for the forum browse criteria. */ - public ChatResponse avatarMessage(AvatarMessage config) { - config.addCredentials(this); - String xml = POST(this.url + "/avatar-message", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ChatResponse response = new ChatResponse(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Process the speech message and return the server generate text-to-speech audio file. - * This allows for server-side speech generation. - * - * @param config config - * @return tts - */ - public String tts(Speech config) { - config.addCredentials(this); - return POST(this.url + "/speak", config.toXML()); - } - - /** - * Return the administrators of the content. - * - * @param config config - * @return Return the administrators of the content. - */ - public List getAdmins(WebMediumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-" + config.getType() + "-admins", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - UserConfig user = new UserConfig(); - user.parseXML((Element)root.getChildNodes().item(index)); - users.add(user.user); - } - return users; - } - - /** - * Return the list of user details for the comma separated values list of user ids. - * - * @param usersCSV usersCSV - * @return getUsers - */ - public List getUsers(String usersCSV) { - UserConfig config = new UserConfig(); - config.user = usersCSV; - config.addCredentials(this); - String xml = POST(this.url + "/get-users", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - Element child = (Element)root.getChildNodes().item(index); - UserConfig userConfig = new UserConfig(); - userConfig.parseXML(child); - users.add(userConfig); - } - return users; - } - - /** - * Return the list of forum posts for the forum browse criteria. - * - * @param config config - * @return Return the list of forum posts for the forum browse criteria. - */ - public List getPosts(BrowseConfig config) { + public List getPosts(BrowseConfig config) { config.addCredentials(this); String xml = POST(this.url + "/get-forum-posts", config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { ForumPostConfig post = new ForumPostConfig(); post.parseXML((Element)root.getChildNodes().item(index)); @@ -1066,491 +633,6 @@ public class SDKConnection { } return instances; } - - /** - * Return the list of issues for the issue tracker browse criteria. - * - * @param config config - * @return Return the list of issues for the issue tracker browse criteria. - */ - public List getIssues(BrowseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-issues", config.toXML()); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - IssueConfig issue = new IssueConfig(); - issue.parseXML((Element)root.getChildNodes().item(index)); - instances.add(issue); - } - return instances; - } - - /** - * Return the list of categories for the type, and domain. - * - * @param config config - * @return Return the list of categories for the type, and domain. - */ - public List getCategories(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-categories", config.toXML()); - List categories = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return categories; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ContentConfig category = new ContentConfig(); - category.parseXML((Element)root.getChildNodes().item(index)); - categories.add(category); - } - return categories; - } - - /** - * Return the list of tags for the type, and domain. - * - * @param config config - * @return Return the list of tags for the type, and domain. - */ - public List getTags(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-tags", config.toXML()); - List tags = new ArrayList(); - tags.add(""); - Element root = parse(xml); - if (root == null) { - return tags; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - tags.add(((Element)root.getChildNodes().item(index)).getAttribute("name")); - } - return tags; - } - - /** - * Return the list of bot templates. - * - * @return Return the list of bot templates. - */ - - //return the list of templates with the pictures. - public List getTemplates() { - String xml = GET(this.url + "/get-all-templates"); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - InstanceConfig instance = new InstanceConfig(); - instance.parseXML((Element)root.getChildNodes().item(index)); - instances.add(instance); - } - return instances; - } - - /** - * Return the users for the content. - * - * @param config config - * @return Return the users for the content. - */ - public List getUsers(WebMediumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-" + config.getType() + "-users", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - UserConfig user = new UserConfig(); - user.parseXML((Element)root.getChildNodes().item(index)); - users.add(user.user); - } - return users; - } - - /** - * Return the channel's bot configuration. - * - * @param config config - * @return Return the channel's bot configuration. - */ - public BotModeConfig getChannelBotMode(ChannelConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-channel-bot-mode", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - BotModeConfig botMode = new BotModeConfig(); - botMode.parseXML(root); - return botMode; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Save the channel's bot configuration. - * - * @param config config - */ - public void saveChannelBotMode(BotModeConfig config) { - config.addCredentials(this); - POST(this.url + "/save-channel-bot-mode", config.toXML()); - } - - /** - * Save the forum's bot configuration. - * - * @param config config - */ - public void saveForumBotMode(BotModeConfig config) { - config.addCredentials(this); - POST(this.url + "/save-forum-bot-mode", config.toXML()); - } - - /** - * Save the bot's learning configuration. - * - * @param config config - */ - public void saveLearning(LearningConfig config) { - config.addCredentials(this); - POST(this.url + "/save-learning", config.toXML()); - } - - /** - * Save the bot's voice configuration. - * - * @param config config - */ - public void saveVoice(VoiceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-voice", config.toXML()); - } - - /** - * Save the bot's avatar configuration. - * - * @param config config - */ - public void saveBotAvatar(InstanceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-bot-avatar", config.toXML()); - } - - - /** - * Perform the user administration task (add or remove users, or administrators). - * - * @param config config - */ - public void userAdmin(UserAdminConfig config) { - config.addCredentials(this); - POST(this.url + "/user-admin", config.toXML()); - } - - /** - * Save the image as the avatar's background. - * - * @param file file - * @param config config - */ - public void saveAvatarBackground(String file, AvatarMedia config) { - config.addCredentials(this); - POSTIMAGE(this.url + "/save-avatar-background", file, config.name, config.toXML()); - } - - /** - * Add the avatar media file to the avatar. - * - * @param file file - * @param config config - */ - public void createAvatarMedia(String file, AvatarMedia config) { - config.addCredentials(this); - if ((file.indexOf(".jpg") != -1) || (file.indexOf(".jpeg") != -1)) { - if (config.hd) { - POSTHDIMAGE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } else { - POSTIMAGE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } - } else { - POSTFILE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } - } - - /** - * Add the graphic media file to the graphic. - * - * @param file file - * @param config config - */ - public void createGraphicMedia(String file, GraphicConfig config) { - config.addCredentials(this); - if ((file.indexOf(".jpg") != -1) || (file.indexOf(".jpeg") != -1)) { - POSTIMAGE(this.url + "/update-graphic-media", file, config.fileName, config.toXML()); - } else { - POSTFILE(this.url + "/update-graphic-media", file, config.fileName, config.toXML()); - } - } - - /** - * Update the contents icon. - * The file will be uploaded to the server. - * - * @param file file - * @param config config - * @param - * @return updateIcon - */ - @SuppressWarnings("unchecked") - public T updateIcon(String file, T config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-" + config.getType() + "-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = (T)config.getClass().newInstance(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the user's icon. - * - * @param file file - * @param config config - * @return Update the user's icon. - */ - public UserConfig updateIcon(String file, UserConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-user-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new UserConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * POSTIMAGE - * - * @param url url - * @param file file - * @param name name - * @param xml xml - * @return POSTIMAGE - */ - public String POSTIMAGE(String url, String file, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("file: " + file); - System.out.println("XML: " + xml); - } - String result = ""; - return result; - } - - /** - * POSTIMAGE - * - * @param url url - * @param bitmap bitmap - * @param name name - * @param xml xml - * @return POSTIMAGE - */ - public String POSTIMAGE(String url, PixelMap bitmap, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("XML: " + xml); - } - String result = ""; - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - byte[] byte_arr = stream.toByteArray(); - ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); - - MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); - - multipartEntity.addPart("file", fileBody); - multipartEntity.addPart("xml", new StringBody(xml)); - - HttpClient httpclient = new DefaultHttpClient(); - HttpResponse response = null; - - HttpPost httppost = new HttpPost(url); - httppost.setEntity(multipartEntity); - response = httpclient.execute(httppost); - - HttpEntity entity = response.getEntity(); - if (entity != null) { - result = EntityUtils.toString(entity, HTTP.UTF_8); - } - - if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { - this.exception = new SDKException("" - + response.getStatusLine().getStatusCode() - + " : " + result); - throw this.exception; - } - - } catch (Exception exception) { - this.exception = new SDKException(exception); - throw this.exception; - } - return result; - } - - /** - * POSTHDIMAGE - * - * @param url url - * @param file file - * @param name name - * @param xml xml - * @return POSTHDIMAGE - */ - public String POSTHDIMAGE(String url, String file, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("file: " + file); - System.out.println("XML: " + xml); - } - String result = ""; - return result; - } - - /** - * POSTFILE - * - * @param url url - * @param path path - * @param name name - * @param xml xml - * @return POSTFILE - */ - public String POSTFILE(String url, String path, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("file: " + path); - System.out.println("XML: " + xml); - } - String result = ""; - try { - File file = new File(path); - FileInputStream stream = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - int read = 0; - byte[] buffer = new byte[4096]; - while ((read = stream.read(buffer)) != -1 ) { - output.write(buffer, 0, read); - } - byte[] byte_arr = output.toByteArray(); - stream.close(); - ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); - - MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); - - multipartEntity.addPart("file", fileBody); - multipartEntity.addPart("xml", new StringBody(xml)); - - HttpClient httpclient = new DefaultHttpClient(); - HttpResponse response = null; - - HttpPost httppost = new HttpPost(url); - httppost.setEntity(multipartEntity); - response = httpclient.execute(httppost); - - HttpEntity entity = response.getEntity(); - if (entity != null) { - result = EntityUtils.toString(entity, HTTP.UTF_8); - } - - if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { - this.exception = new SDKException("" - + response.getStatusLine().getStatusCode() - + " : " + result); - throw this.exception; - } - - } catch (Exception exception) { - this.exception = new SDKException(exception); - throw this.exception; - } - return result; - } - - /** - * Return the forum's bot configuration. - * - * @param config config - * @return Return the forum's bot configuration. - */ - public BotModeConfig getForumBotMode(ForumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-forum-bot-mode", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - BotModeConfig botMode = new BotModeConfig(); - botMode.parseXML(root); - return botMode; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Return the bot's voice configuration. - * - * @param config config - * @return Return the bot's voice configuration. - */ - public VoiceConfig getVoice(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-voice", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - VoiceConfig voice = new VoiceConfig(); - voice.parseXML(root); - return voice; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Return the bot's default responses. * @@ -1562,82 +644,11 @@ public class SDKConnection { String xml = POST(this.url + "/get-default-responses", config.toXML()); List defaultResponses = new ArrayList(); Element root = parse(xml); - if (root == null) { - return defaultResponses; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { defaultResponses.add(((Element)root.getChildNodes().item(index)).getChildNodes().item(0).getTextContent()); } return defaultResponses; } - - /** - * Search the bot's responses. - * - * @param config config - * @return Search the bot's responses. - */ - public List getResponses(ResponseSearchConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-responses", config.toXML()); - List responses = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return responses; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ResponseConfig response = new ResponseConfig(); - response.parseXML((Element)root.getChildNodes().item(index)); - responses.add(response); - } - return responses; - } - - /** - * Search the bot's conversations. - * - * @param config config - * @return Search the bot's conversations. - */ - public List getConversations(ResponseSearchConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-conversations", config.toXML()); - List conversations = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return conversations; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ConversationConfig response = new ConversationConfig(); - response.parseXML((Element)root.getChildNodes().item(index)); - conversations.add(response); - } - return conversations; - } - - /** - * Return the bot's learning configuration. - * - * @param config config - * @return Return the bot's learning configuration. - */ - public LearningConfig getLearning(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-learning", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - LearningConfig learning = new LearningConfig(); - learning.parseXML(root); - return learning; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Return the list of content for the browse criteria. * The type defines the content type (one of Bot, Forum, Channel, Domain). @@ -1657,9 +668,6 @@ public class SDKConnection { String xml = POSTUpdate(ability,this.url + type, config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { WebMediumConfig instance = null; if (config.type.equals("Bot")) { @@ -1682,176 +690,13 @@ public class SDKConnection { } return instances; } - - /** - * Return the list of media for the avatar. - * - * @param config config - * @return Return the list of media for the avatar. - */ - public List getAvatarMedia(AvatarConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-avatar-media", config.toXML()); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - AvatarMedia instance = new AvatarMedia(); - instance.parseXML((Element)root.getChildNodes().item(index)); - instances.add(instance); - } - return instances; - } - - /** - * Return the script source - * - * @param config config - * @return Return the script source - */ - public ScriptSourceConfig getScriptSource(ScriptConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-script-source", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ScriptSourceConfig script = new ScriptSourceConfig(); - script.parseXML(root); - return script; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create or update script - Save the script source - * - * @param config config - */ - public void saveScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-script-source", config.toXML()); - } - - /** - * Return the source code for a single bot script - * - * @param config config - * @return Return the source code for a single bot script - */ - public ScriptSourceConfig getBotScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-bot-script-source", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ScriptSourceConfig botScript = new ScriptSourceConfig(); - botScript.parseXML(root); - return botScript; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Return a list of the bots scripts - * - * @param config config - * @return Return a list of the bots scripts - */ - public List getBotScripts(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-bot-scripts", config.toXML()); - List botScripts = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return botScripts; - } - for (int i = 0; i < root.getChildNodes().getLength(); i++) { - ScriptConfig script = new ScriptConfig(); - script.parseXML((Element)root.getChildNodes().item(i)); - botScripts.add(script); - } - return botScripts; - } - - /** - * import a script to the bot - * - * @param config config - */ - - public void importBotScript(ScriptConfig config) { - config.addCredentials(this); - POST(this.url + "/import-bot-script", config.toXML()); - } - - /** - * import a chatlog/response list to the bot - * - * @param config config - */ - public void importBotLog(ScriptConfig config) { - config.addCredentials(this); - POST(this.url + "/import-bot-log", config.toXML()); - } - - - /** - * Save the bot script source - * - * @param config config - */ - public void saveBotScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-bot-script-source", config.toXML()); - } - - /** - * Delete selected bot script - * - * @param config config - */ - public void deleteBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/delete-bot-script", config.toXML()); - } - - /** - * Move up one bot script - * - * @param config config - */ - public void upBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/up-bot-script", config.toXML()); - } - - /** - * Move down one bot script - * - * @param config config - */ - public void downBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/down-bot-script", config.toXML()); - } - /** * Return the list of content types. * * @return Return the list of content types. */ public String[] getTypes() { - return types; + return types.clone(); } /** @@ -1860,7 +705,7 @@ public class SDKConnection { * @return Return the access mode types. */ public String[] getAccessModes() { - return accessModes; + return accessModes.clone(); } /** @@ -1869,7 +714,7 @@ public class SDKConnection { * @return Return the media access mode types. */ public String[] getMediaAccessModes() { - return mediaAccessModes; + return mediaAccessModes.clone(); } /** diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java index 9936a355955e7bfd40d42fed9275a401996b5ada..e774eb9d4581652244f5fac80c0695bba544daea 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java @@ -1,21 +1,3 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.ability; import ohos.aafwk.ability.Ability; @@ -34,11 +16,7 @@ import ohos.agp.components.element.StateElement; import ohos.agp.components.webengine.JsCallback; import ohos.agp.components.webengine.WebView; import ohos.agp.utils.LayoutAlignment; -import ohos.agp.window.dialog.IDialog; import ohos.agp.window.dialog.PopupDialog; -import ohos.agp.window.service.Display; -import ohos.agp.window.service.DisplayAttributes; -import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.WindowManager; import ohos.ai.asr.AsrClient; import ohos.ai.asr.AsrIntent; @@ -55,20 +33,16 @@ import ohos.eventhandler.EventRunner; import ohos.eventhandler.InnerEvent; import ohos.media.audio.AudioManager; import ohos.media.audio.AudioRemoteException; -import ohos.media.common.Source; import ohos.media.image.PixelMap; import ohos.media.player.Player; import ohos.multimodalinput.event.TouchEvent; import ohos.utils.PacMap; -import ohos.utils.net.Uri; -import ohos.utils.zson.ZSONObject; import org.botlibre.sdk.MainAbility; import org.botlibre.sdk.ResourceTable; import org.botlibre.sdk.ability.actions.HttpAction; import org.botlibre.sdk.ability.actions.HttpChatAction; import org.botlibre.sdk.ability.actions.HttpFetchChatAvatarAction; import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChatConfig; import org.botlibre.sdk.config.ChatResponse; import org.botlibre.sdk.config.InstanceConfig; @@ -76,9 +50,7 @@ import org.botlibre.sdk.config.VoiceConfig; import org.botlibre.sdk.provider.ChatListProvicer; import org.botlibre.sdk.util.LogUtils; import org.botlibre.sdk.util.PreferencesUtils; -import org.botlibre.sdk.util.ResUtil; import org.botlibre.sdk.util.ResUtils; -import org.botlibre.sdk.util.ShapeUtils; import org.botlibre.sdk.util.TextStream; import org.botlibre.sdk.util.ToastUtils; import org.botlibre.sdk.util.Utils; @@ -86,29 +58,26 @@ import org.botlibre.sdk.util.Utils; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import java.util.Random; import java.util.UUID; /** * Ability for chatting with a bot. * To launch this Ability from your app you can use the HttpFetchAction passing the bot id or name as a config, and launch=true. + * + * @since 2021-05-10 */ @SuppressWarnings("deprecation") public class ChatAbility extends LibreAbility { - protected static final int RESULT_SPEECH = 1; protected static final int CAPTURE_IMAGE = 2; - protected static final int RESULT_SCAN = 3; - protected static final int CAPTURE_VIDEO = 4; private static final int LIST_CONTAINER = 7; private static final int BEGIN_LISTENING = 8; - protected static boolean DEBUG; + private static boolean DEBUG; - public static Ability ability; + private static Ability ability; private boolean isRecording; - public static boolean isListening; + private static boolean isListening; private EventHandler handler = new EventHandler(EventRunner.current()) { @@ -142,9 +111,9 @@ public class ChatAbility extends LibreAbility { * 语音识别客户端 */ private AsrClient asrClient; - public Component videoLayout; - public Image bigImage; - protected TextField editText; + private Component videoLayout; + private Image bigImage; + private TextField editText; private boolean volumeChecked = true; private Thread thread; @@ -164,17 +133,16 @@ public class ChatAbility extends LibreAbility { protected InstanceConfig instance; private int stateLayouts = 0; private ListContainer scrollView; - public boolean music = false; private double lastReply = System.currentTimeMillis(); - public static List messages = new ArrayList(); + private List messages = new ArrayList(); public ChatResponse response; - public Player audioPlayer; - public String currentAudio; + private Player audioPlayer; + private String currentAudio; - public boolean videoError; - protected volatile boolean wasSpeaking; + private boolean videoError; + private volatile boolean wasSpeaking; private boolean active = true; @@ -182,17 +150,17 @@ public class ChatAbility extends LibreAbility { protected String avatarId; protected boolean changingVoice; Player speechPlayer; - protected Random random = new Random(); - protected PixelMap icon; //flag will check if the mic is ON or OFF - public static boolean micLastStat; + private static boolean micLastStat; - private boolean failedOfflineLanguage = false; private boolean threadIsOn = false; + + + /** * 文本转语音 语音播报 */ @@ -252,7 +220,7 @@ public class ChatAbility extends LibreAbility { @Override public void onEvent(int eventType, PacMap pacMap) { if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) { - VoiceConfig voice = MainAbility.voice; + VoiceConfig voice = MainAbility.getVoice(); float pitch = 1; if (voice != null && voice.pitch != null && voice.pitch.length() > 0) { try { @@ -396,7 +364,6 @@ public class ChatAbility extends LibreAbility { restartListening(); } else if (error == AsrError.ERROR_SERVER) { LogUtils.sop("Error: Server Error"); - failedOfflineLanguage = true; restartListening(); } else if (error == AsrError.ERROR_SPEECH_TIMEOUT) { LogUtils.sop("Error: NO speech input"); @@ -467,7 +434,7 @@ public class ChatAbility extends LibreAbility { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); //For "scream" issue - micLastStat = MainAbility.listenInBackground; + micLastStat = MainAbility.isListenInBackground(); getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS); tvTitle = ((Text) findComponentById(ResourceTable.Id_title)); @@ -477,14 +444,14 @@ public class ChatAbility extends LibreAbility { ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { setMicIcon(false, false); - } else if (!MainAbility.listenInBackground) { + } else if (!MainAbility.isListenInBackground()) { setMicIcon(false, false); } //Last time will be saved for the MIC. - if (MainAbility.listenInBackground && MainAbility.handsFreeSpeech) { + if (MainAbility.isListenInBackground() && MainAbility.isHandsFreeSpeech()) { microphoneThread(thread); } @@ -508,8 +475,6 @@ public class ChatAbility extends LibreAbility { bigImage = (Image) findComponentById(ResourceTable.Id_bigImage); videoLayout = findComponentById(ResourceTable.Id_videoLayout); - - resetVideoErrorListener(); videoError = false; editText.setFocusChangedListener((component, isFocused) -> { @@ -519,7 +484,7 @@ public class ChatAbility extends LibreAbility { } }); - if (MainAbility.translate) { + if (MainAbility.isTranslate()) { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); } else { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); @@ -536,17 +501,17 @@ public class ChatAbility extends LibreAbility { }); micButton.setClickedListener(component -> { - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { //set the current volume to the setting. setStreamVolume(); //if its ON Or OFF - Switching back and forth - MainAbility.listenInBackground = !MainAbility.listenInBackground; + MainAbility.setListenInBackground(!MainAbility.isListenInBackground()); //saving the boolean data of MainAbility.listeningInBackground Preferences cookies = PreferencesUtils.getPreferences(ability); - cookies.putBoolean("listenInBackground", MainAbility.listenInBackground); + cookies.putBoolean("listenInBackground", MainAbility.isListenInBackground()); cookies.flushSync(); - if (MainAbility.listenInBackground) { + if (MainAbility.isListenInBackground()) { micLastStat = true; try { microphoneThread(thread); @@ -628,7 +593,7 @@ public class ChatAbility extends LibreAbility { case TouchEvent.POINT_MOVE: return true; case TouchEvent.PRIMARY_POINT_UP: - boolean isVideo = !MainAbility.disableVideo && !videoError && response != null + boolean isVideo = !MainAbility.isDisableVideo() && !videoError && response != null && response.isVideo(); videoLayout = findComponentById(ResourceTable.Id_videoLayout); if (bigImage.getVisibility() == Component.VISIBLE) { @@ -672,18 +637,17 @@ public class ChatAbility extends LibreAbility { }); final ChatConfig config = new ChatConfig(); - //config.instance = instance.id; config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; + config.avatarHD = MainAbility.isHd(); + config.speak = !MainAbility.isDeviceVoice(); // This is required because of a bug in TextToSpeech that prevents onInit being called if an AsynchTask is called... Thread thread1 = new Thread() { public void run() { @@ -705,10 +669,15 @@ public class ChatAbility extends LibreAbility { } - //thread for the Microphone + /** + * microphoneThread + * + * @param thread + * @return dd + */ public Thread microphoneThread(Thread thread) { //make sure its on if it didn't turn off by the user. if 'sleep' is called it will turn the mic off. - if (MainAbility.listenInBackground && threadIsOn) { + if (MainAbility.isListenInBackground() && threadIsOn) { return thread; } //if the user clicked on the Mic while its ON it will turn off and turn the thread off as well. @@ -749,37 +718,7 @@ public class ChatAbility extends LibreAbility { return thread; } - public void resetChat(Component view) { - ChatConfig config = new ChatConfig(); - //config.instance = instance.id; - config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; - } - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; - HttpAction action = new HttpChatAction(ChatAbility.this, config); - action.execute(); - - editText.setText(""); - messages.clear(); - - //主线程 - handler.sendEvent(LIST_CONTAINER); - - webView.load(null, "", "text/html", "utf-8", null); - } - - public void menuList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void menuList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_menu_chat, null, false); @@ -788,11 +727,11 @@ public class ChatAbility extends LibreAbility { DirectionalLayout.LayoutConfig.MATCH_CONTENT); menuDialog.showOnCertainPosition(LayoutAlignment.BOTTOM | LayoutAlignment.LEFT, 10, 280); menuDialog.setAutoClosable(true); - Component.ClickedListener listener=new Component.ClickedListener() { + Component.ClickedListener listener = new Component.ClickedListener() { @Override public void onClick(Component component) { stopListening(); - switch (component.getId()){ + switch (component.getId()) { case ResourceTable.Id_menuItem1: toggleSound(); break; @@ -800,7 +739,6 @@ public class ChatAbility extends LibreAbility { toggleDeviceVoice(); break; case ResourceTable.Id_menuItem3: - changeLanguage(null); break; case ResourceTable.Id_menuItem4: MicConfiguration(); @@ -809,10 +747,10 @@ public class ChatAbility extends LibreAbility { toggleDisableVideo(); break; case ResourceTable.Id_menuItem6: - MainAbility.webm = !MainAbility.webm; + MainAbility.setWebm(!MainAbility.isWebm()); break; case ResourceTable.Id_menuItem7: - MainAbility.hd = !MainAbility.hd; + MainAbility.setHd(!MainAbility.isHd()); break; } } @@ -832,16 +770,13 @@ public class ChatAbility extends LibreAbility { private void setCheckBoxShape(Checkbox... checkBoxs) { StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this, ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this, ResourceTable.Media_unchecked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this, ResourceTable.Media_checked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this, ResourceTable.Media_unchecked)); for (Checkbox checkbox : checkBoxs) { checkbox.setButtonElement(stateElement); } } - public void resetVideoErrorListener() { - } - @Override protected void onAbilityResult(int requestCode, int resultCode, Intent data) { super.onAbilityResult(requestCode, resultCode, data); @@ -853,103 +788,27 @@ public class ChatAbility extends LibreAbility { } } - public void flagResponse() { - MainAbility.confirm("Flag bad response?", this, true, (iDialog, i) -> { - switch (i) { - case IDialog.BUTTON1: - ChatConfig config = new ChatConfig(); - //config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; - config.avatar = avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; - } - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - - config.message = "flag"; //text.getText().toString().trim(); - if (config.message.equals("")) { - return; - } - messages.add(config); - handler.sendEvent(LIST_CONTAINER); - - - config.offensive = true; - - - HttpChatAction action = new HttpChatAction(ChatAbility.this, config); - action.execute(); - - editText.setText(""); - resetToolbar(); - - webView.load(null, "thinking...", "text/html", "utf-8", null); - break; - case IDialog.BUTTON2: - break; - } - }); - } - - public void submitCorrection() { - final TextField text = new TextField(this); - MainAbility.prompt("Enter correction to the bot's response (what it should have said)", this, text, (iDialog, i) -> { - ChatConfig config = new ChatConfig(); - // config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; - config.avatar = avatarId; - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - - config.message = text.getText().toString().trim(); - if (config.message.equals("")) { - return; - } - messages.add(config); - - handler.sendEvent(LIST_CONTAINER); - - - config.correction = true; - - resetToolbar(); - - webView.load(null, "thinking...", "text/html", "utf-8", null); - }); - } - - public void submitChat() { + private void submitChat() { ChatConfig config = new ChatConfig(); //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); config.message = editText.getText().toString().trim(); if (config.message.equals("")) { return; } - this.messages.add(config); + messages.add(config); handler.sendEvent(LIST_CONTAINER); @@ -979,100 +838,43 @@ public class ChatAbility extends LibreAbility { stopListening(); //its Important for "sleep" "scream" ...etc commands. //this will turn off the mic - MainAbility.listenInBackground = false; + MainAbility.setListenInBackground(false); } - public void toggleSound() { - MainAbility.sound = !MainAbility.sound; + private void toggleSound() { + MainAbility.setSound(!MainAbility.isSound()); resetToolbar(); } - public void toggleHandsFreeSpeech() { - MainAbility.handsFreeSpeech = !MainAbility.handsFreeSpeech; - if (!MainAbility.handsFreeSpeech) { - stopListening(); - } else if (MainAbility.handsFreeSpeech) { - beginListening(); - } - Preferences cookies = PreferencesUtils.getPreferences(this.ability); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); - cookies.flushSync(); - } - - public void toggleDisableVideo() { + private void toggleDisableVideo() { if (this.videoError) { this.videoError = false; - MainAbility.disableVideo = false; + MainAbility.setDisableVideo(false); } else { - MainAbility.disableVideo = !MainAbility.disableVideo; + MainAbility.setDisableVideo(!MainAbility.isDisableVideo()); } } - public void changeAvatar() { - if (MainAbility.online) { - MainAbility.browsing = true; - BrowseConfig config = new BrowseConfig(); - config.type = "Avatar"; - config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; - } else { -// Intent intent = getIntent(ability, AvatarSelection.class.getName()); -// startAbility(intent); - } - } - public void changeVoice() { - this.changingVoice = true; -// Intent intent = getIntent(ability, ChangeVoiceAbility.class.getName()); -// startAbility(intent); + private void toggleDeviceVoice() { + MainAbility.setDeviceVoice(!MainAbility.isDeviceVoice()); } - public void toggleDeviceVoice() { - MainAbility.deviceVoice = !MainAbility.deviceVoice; - } - - public void toggleFlag(Component view) { - flagResponse(); - } - - public void toggleCorrection(Component view) { - submitCorrection(); - } - - - public void changeLanguage(Component view) { -// MainAbility.changeLanguage(this, (IDialog.ClickedListener) (iDialog, i) -> { -// resetTTS(); -// if (MainAbility.translate) { -// findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); -// } else { -// findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); -// } -// }); - - - } - - public void resetToolbar() { - if (MainAbility.sound) { - ShapeUtils.setBackground(soundButton,ResourceTable.Media_sound); + private void resetToolbar() { + if (MainAbility.isSound()) { + ResUtils.setBackground(soundButton, ResourceTable.Media_sound); } else { - ShapeUtils.setBackground(soundButton,ResourceTable.Media_mute); + ResUtils.setBackground(soundButton, ResourceTable.Media_mute); } } @Override public void onActive() { - MainAbility.searching = false; - MainAbility.searchingPosts = false; - if (MainAbility.browsing && (MainAbility.instance instanceof AvatarConfig)) { - if (MainAbility.user == null || MainAbility.user.type == null || MainAbility.user.type.isEmpty() || MainAbility.user.type.equals("Basic")) { - //MainAbility.showMessage("You must upgrade to get access to this avatar", this); - //super.onResume(); - //return; - } - this.avatar = (AvatarConfig) MainAbility.instance; + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + if (MainAbility.isBrowsing() && (MainAbility.getInstance() instanceof AvatarConfig)) { + this.avatar = (AvatarConfig) MainAbility.getInstance(); this.avatarId = this.avatar.id; if (this.bigImage.getVisibility() == Component.HIDE) { this.bigImage.setVisibility(Component.VISIBLE); @@ -1080,19 +882,11 @@ public class ChatAbility extends LibreAbility { if (this.videoLayout.getVisibility() == Component.VISIBLE) { this.videoLayout.setVisibility(Component.HIDE); } - -// HttpGetImageAction.fetchImage(this, this.avatar.avatar, this.bigImage); - AvatarConfig avatarConfig = (AvatarConfig) this.avatar.credentials(); HttpFetchChatAvatarAction action = new HttpFetchChatAvatarAction(this, avatarConfig); action.execute(); } - MainAbility.browsing = false; - if ((MainAbility.instance instanceof InstanceConfig) && MainAbility.instance.id.equals(this.instance.id)) { - //this.instance = (InstanceConfig) MainAbility.instance; - } else { - //MainAbility.instance = this.instance; - } + MainAbility.setBrowsing(false); if (this.changingVoice) { this.changingVoice = false; resetTTS(); @@ -1100,14 +894,14 @@ public class ChatAbility extends LibreAbility { super.onActive(); } - public void resetTTS() { + private void resetTTS() { ttsClient.stopSpeak(); ttsClient.release(); ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); } - public String getAvatarIcon(ChatResponse config) { + private String getAvatarIcon(ChatResponse config) { if (this.avatar != null) { return this.avatar.avatar; } @@ -1117,16 +911,8 @@ public class ChatAbility extends LibreAbility { return config.avatar; } - public void resetAvatar(AvatarConfig config) { -// HttpGetImageAction.fetchImage(this, config.avatar, this.bigImage); -// HttpGetImageAction.fetchImage(this, config.avatar, (Image) findComponentById(ResourceTable.Id_responseImageView)); - } - - public void MicConfiguration() { - ToastUtils.show(ability,"打开麦克风配置"); -// Intent intent = getIntent(ability, MicConfiguration.class.getName()); -// startAbility(intent); -// terminateAbility(); + private void MicConfiguration() { + ToastUtils.show(ability, "打开麦克风配置"); } @Override @@ -1142,7 +928,7 @@ public class ChatAbility extends LibreAbility { if (this.instance != null) { ChatConfig config = new ChatConfig(); //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; + config.conversation = MainAbility.getConversation(); config.disconnect = true; HttpChatAction action = new HttpChatAction(this, config); @@ -1240,7 +1026,7 @@ public class ChatAbility extends LibreAbility { return html; } - public void response(final ChatResponse response) { + private void response(final ChatResponse response) { if (speechPlayer != null || ttsClient != null) { try { ttsClient.stopSpeak(); @@ -1272,13 +1058,6 @@ public class ChatAbility extends LibreAbility { status = status + response.pose; } LogUtils.sop("response.command: " + response.command); - if (response.command != null) { - ZSONObject jsonObject = response.getCommand(); - //Command command = new Command(this, jsonObject); - - } - - Text statusView = (Text) findComponentById(ResourceTable.Id_statusText); statusView.setText(status); @@ -1299,121 +1078,28 @@ public class ChatAbility extends LibreAbility { } webView.load(null, html, "text/html", "utf-8", null); - boolean talk = (text.trim().length() > 0) && (MainAbility.deviceVoice || (this.response.speech != null && this.response.speech.length() > 0)); - if (MainAbility.sound && talk) { - if (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { - playVideo(this.response.avatarTalk, false); - } else if (talk) { + boolean talk = (text.trim().length() > 0) && (MainAbility.isDeviceVoice() || (this.response.speech != null && this.response.speech.length() > 0)); + if (MainAbility.isSound() && talk) { + if (!MainAbility.isDisableVideo() && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { } - } else if (talk && (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.avatarTalk != null)) { - playVideo(this.response.avatarTalk, false); + } else if (talk && (!MainAbility.isDisableVideo() && !videoError && this.response.isVideo() && this.response.avatarTalk != null)) { handler.sendEvent(BEGIN_LISTENING); - } else { - handler.sendEvent(BEGIN_LISTENING); } } catch (Exception exception) { LogUtils.sop(exception.getMessage()); } if (micLastStat) { - MainAbility.listenInBackground = true; + MainAbility.setListenInBackground(true); } } @Override protected void onInactive() { stopListening(); - //muteMicBeep(false); super.onInactive(); } - - public void playVideo(String video, boolean loop) { - } - - public void cycleVideo(final ChatResponse response) { - } - - public Player playAudio(String audio, boolean loop, boolean cache, boolean start) { - try { - Uri audioUri = null; - if (cache) { - } - if (audioUri == null) { - audioUri = Uri.parse(MainAbility.connection.fetchImage(audio).toURI().toString()); - } - final Player audioPlayer = new Player(ability); - audioPlayer.setSource(new Source(String.valueOf(audioUri))); - audioPlayer.setPlayerCallback(new Player.IPlayerCallback() { - @Override - public void onPrepared() { - - } - - @Override - public void onMessage(int i, int i1) { - - } - - @Override - public void onError(int errorType, int errorCode) { - LogUtils.sop("errorCode" + errorCode); - audioPlayer.stop(); - audioPlayer.release(); - } - - @Override - public void onResolutionChanged(int i, int i1) { - - } - - @Override - public void onPlayBackComplete() { - audioPlayer.release(); - handler.sendEvent(BEGIN_LISTENING); - - } - - @Override - public void onRewindToComplete() { - - } - - @Override - public void onBufferingChange(int i) { - - } - - @Override - public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) { - - } - - @Override - public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) { - - } - }); - audioPlayer.prepare(); - audioPlayer.enableSingleLooping(loop); - if (start) { - audioPlayer.play(); - } - return audioPlayer; - } catch (Exception exception) { - LogUtils.sop(exception.toString()); - return null; - } - } - - public List getMessages() { - return messages; - } - - public void setMessages(List messages) { - this.messages = messages; - } - public ChatResponse getResponse() { return response; } @@ -1461,7 +1147,7 @@ public class ChatAbility extends LibreAbility { private void restartListening() { lastReply = System.currentTimeMillis(); debug("restartListening"); - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { return; } if (!isListening) { @@ -1470,10 +1156,6 @@ public class ChatAbility extends LibreAbility { handler.sendEvent(BEGIN_LISTENING); } - - public void scanBarcode(Component v) { - } - private void setMicIcon(boolean on, boolean recording) { try { if (!on) { @@ -1489,7 +1171,7 @@ public class ChatAbility extends LibreAbility { } - public void debug(final String text) { + private void debug(final String text) { if (!DEBUG) { return; } @@ -1501,16 +1183,16 @@ public class ChatAbility extends LibreAbility { private void muteMicBeep(boolean mute) { - debug("muteMicBeep:" + mute + ":" + MainAbility.volume); + debug("muteMicBeep:" + mute + ":" + MainAbility.getVolume()); AudioManager audioManager = new AudioManager(ability); if (mute) { LogUtils.sop("muteMicBeep : " + 0); //if its true then the Volume will be zero. audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } else { - LogUtils.sop("muteMicBeep : " + MainAbility.volume); + LogUtils.sop("muteMicBeep : " + MainAbility.getVolume()); //if its false, the Volume will put back on - audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.volume); + audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.getVolume()); } } @@ -1525,7 +1207,7 @@ public class ChatAbility extends LibreAbility { if (volume != 0) { debug("setStreamVolume:" + volume); LogUtils.sop("setStreamVolume : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -1534,15 +1216,15 @@ public class ChatAbility extends LibreAbility { setStreamVolume(); debug("beginListening:"); try { - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { return; } - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { muteMicBeep(true); isListening = true; } - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { muteMicBeep(false); return; } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java index a27cd18b1299f79d087d4d640da74ea508ca3cc2..1cf1b8451403a29dc1e04a03aa8c7a7e832a01b2 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java @@ -18,10 +18,6 @@ package org.botlibre.sdk.ability; -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpCreateUserAction; -import org.botlibre.sdk.config.UserConfig; -import org.botlibre.sdk.util.ResUtil; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Checkbox; @@ -29,6 +25,9 @@ import ohos.agp.components.Component; import ohos.agp.components.ComponentState; import ohos.agp.components.TextField; import ohos.agp.components.element.StateElement; +import org.botlibre.sdk.ResourceTable; +import org.botlibre.sdk.config.UserConfig; +import org.botlibre.sdk.util.ResUtils; /** * Ability for creating a new user. @@ -58,11 +57,10 @@ public class CreateUserAbility extends LibreAbility { } }); - Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); showNameCheckBox.setButtonElement(stateElement); } @@ -89,9 +87,6 @@ public class CreateUserAbility extends LibreAbility { config.bio = text.getText().toString().trim(); config.showName = showNameCheckBox.isChecked(); - - HttpCreateUserAction action = new HttpCreateUserAction(getContext(),this, config); -// action.execute(); } /** diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java index 343e0d97d9d32d2c82aa950e6e107fca5b995db3..e259b8a65be046f7cf53dd16397a0539a8c112ed 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java @@ -42,16 +42,14 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.ability_help); super.setUIContent(ResourceTable.Layout_ability_help); - MainAbility.online = true; - this.instance = MainAbility.instance; - MainAbility.searching = false; - MainAbility.searchingPosts = false; - //switching to remote Connection. - MainAbility.connection = MainAbility.remoteConnection; + MainAbility.setOnline(true); + this.instance = MainAbility.getInstance(); + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + MainAbility.setConnection(MainAbility.getRemoteConnection()); - MainAbility.instance = this.instance; + MainAbility.setInstance(this.instance); Button faqButton = (Button) findComponentById(ResourceTable.Id_faqButton); @@ -72,34 +70,25 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen ForumConfig instance = new ForumConfig(); instance.domain = ""; instance.name = "FAQ"; - - HttpResultAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void forums() { BrowseConfig config = new BrowseConfig(); config.domain = ""; config.type = "Forum"; - config.contentRating = MainAbility.contentRating; + config.contentRating = MainAbility.getContentRating(); } public void liveSupport() { ChannelConfig instance = new ChannelConfig(); instance.domain = ""; instance.name = "Help"; - - HttpFetchAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void helpBot() { InstanceConfig instance = new InstanceConfig(); instance.domain = ""; instance.name = "Help Bot"; - - HttpFetchAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void website() { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java index 8a30f5710b4f81b71b087f51bfbd8ddbc3784d12..d3e6eba0c25027d0dd8c7a7bc288187912e7fd47 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java @@ -1,110 +1,25 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ package org.botlibre.sdk.ability; -import java.util.ArrayList; -import java.util.List; - -import org.botlibre.sdk.ResourceTable; import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; +import org.botlibre.sdk.ResourceTable; import org.botlibre.sdk.config.OfflineTemplateConfig; -public class ListTemplateView extends /*CreateWebMediumAbility*/Ability { - public static boolean offlineTemplate = false; - List items; +import java.util.ArrayList; +import java.util.List; +public class ListTemplateView extends Ability { final static String listOfBots [] = {"Empty" , "Basic", "Personal Assistance"}; final static int imagesId [] = {ResourceTable.Media_bot, ResourceTable.Media_bot , ResourceTable.Media_bot}; final static String listOfDec [] = {"A completely empty template loaded with no knowledge or scripts.", "A basic bot template with only responses to common greetings and farewells (hello, goodbye, etc.), and the default bootstrap Self language scripts that understand basic language, 'what is' and 'where is' questions, names, dates, math, and topical questions.", "Template for a Virtual Assistant. This template has command scripts for performing common tasks on such as opening apps, scheduling appointments, and send email."}; - -// ArrayAdapter adapter; -// ListView llview; -// Intent data = new Intent(); -// String temp; -// TextView txt; -// @Override -// public String getType() { -// return "Bot"; -// } + @SuppressWarnings("unchecked") @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_list_view); -// llview = (ListView) findViewById(R.id.theListView); -// txt=(TextView) findViewById(R.id.theTitle); -// txt.setText("Select Template"); -// -// if(offlineTemplate){ -// items = retriveTemplates(); -// -// adapter = new CustomListViewAdapter(this, R.layout.list_item_imager, items); -// llview.setAdapter(adapter); -// -// llview.setOnItemClickListener(new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { -// WebMediumConfig config = new InstanceConfig(); -// OfflineTemplateConfig templates = (OfflineTemplateConfig) (llview.getItemAtPosition(arg2)); -// //saving a template number for getting the icons and pictures of the bot -// saveAllData(MainAbility.launchInstanceName = templates.getTitle(), MainAbility.launchInstanceId = templates.getId(), MainAbility.templateID = arg2); -// config.id = MainAbility.launchInstanceId; -// config.name = MainAbility.launchInstanceName; -// AvatarSelection.saveSelectedAvatar(templates.getTitle()); -// MainAbility.readZipAvatars(ListTemplateView.this, templates.getTitle()); -// MainAbility.offlineSelectedImage = templates.getImageId(); -// HttpAction action = new HttpFetchActionOffline(ListTemplateView.this, config, true); -// action.execute(); -// } -// }); -// offlineTemplate = false; -// return; -// } -// -// -// -// adapter = new ImageListAdapter(this, R.layout.image_list, (List) MainAbility.getAllTemplates(this)); -// llview.setAdapter(adapter); -// -// llview.setOnItemClickListener(new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { -// InstanceConfig templates = (InstanceConfig) (llview.getItemAtPosition(arg2)); -// Toast.makeText(ListTemplateView.this, templates.name + " Selected", Toast.LENGTH_SHORT).show(); -// data.putExtra("template", templates.name); -// setResult(RESULT_OK,data); -// finish(); -// } -// }); -// -// HttpAction action = new HttpGetTemplatesAction(this); -// action.execute(); - - } - - public void saveAllData(String instanceId, String instanceName, int id){ -// SharedPreferences.Editor cookies = MainAbility.current.getPreferences(Context.MODE_PRIVATE).edit(); -// cookies.putString("instanceID", instanceId); -// cookies.putString("instanceName", instanceName); -// cookies.putInt("tempId", id); -// cookies.commit(); + } public static List retriveTemplates(){ diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java index 33443529161e668bbe4b0c7cd5cdf6fbe1282b9d..907d776d7b72c07bf09b3a9cf33398d71a395232 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java @@ -18,23 +18,23 @@ package org.botlibre.sdk.ability; -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpConnectAction; -import org.botlibre.sdk.config.UserConfig; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Component; import ohos.agp.components.TextField; +import org.botlibre.sdk.ResourceTable; +import org.botlibre.sdk.config.UserConfig; /** * Ability for user login. + * + * @since 2021-05-10 */ public class LoginAbility extends LibreAbility implements Component.ClickedListener { @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.Ability_login); super.setUIContent(ResourceTable.Layout_ability_login); Button connectButton = (Button)findComponentById(ResourceTable.Id_connectButton); @@ -55,10 +55,11 @@ public class LoginAbility extends LibreAbility implements Component.ClickedListe UserConfig config = new UserConfig(); config.user = user; config.password = password; - HttpConnectAction action = new HttpConnectAction(this, config, true); -// action.execute(); } - + + /** + * signUp + */ public void signUp() { terminateAbility(); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java index 6ec47903d10528cbc5b80da84d2d140af3a1f5c7..bb7465883db391aedab4f906113c4bfb54fe96bd 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java @@ -42,7 +42,7 @@ import org.botlibre.sdk.ability.dialog.SearchDialogBuilder; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.util.PreferencesUtils; -import org.botlibre.sdk.util.ResUtil; +import org.botlibre.sdk.util.ResUtils; import java.util.Optional; @@ -52,11 +52,9 @@ import java.util.Optional; public abstract class SearchAbility extends LibreAbility implements SelectListener { final static int TAGTEXT = 3,CATTEXT = 4; - private TextField tagsText,categoriesText; private Image btnTag, btnCat; private Text sortSpin,restrictSpin; - private boolean sortSpinOption = true; private int type = 0; private RadioButton publicRadio; private RadioButton radio; @@ -102,19 +100,17 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen btnCat = (Image)findComponentById(ResourceTable.Id_btnCat); btnTag = (Image)findComponentById(ResourceTable.Id_btnTag); - tagsText = (TextField) findComponentById(ResourceTable.Id_tagsText); - categoriesText = (TextField)findComponentById(ResourceTable.Id_categoriesText); browseButton = (Button) findComponentById(ResourceTable.Id_browseButton); menuButton = (Button) findComponentById(ResourceTable.Id_menuButton); Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); checkbox.setButtonElement(stateElement); - checkbox.setChecked(MainAbility.showImages); + checkbox.setChecked(MainAbility.isShowImages()); publicRadio = (RadioButton) findComponentById(ResourceTable.Id_publicRadio); publicRadio.setChecked(true); @@ -166,7 +162,7 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen @Override public void onClick(Component component) { type = 2; - SearchDialogBuilder.with(SearchAbility.this,MainAbility.contentRatings).setSelectInterface(SearchAbility.this); + SearchDialogBuilder.with(SearchAbility.this,MainAbility.getContentRatings()).setSelectInterface(SearchAbility.this); } }); @@ -267,8 +263,8 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen // MainAbility.contentRating = (String) contentRating.getSelectedItem(); // config.contentRating = MainAbility.contentRating; //save contentRating - Preferences editor = PreferencesUtils.getPreferences(MainAbility.current); - editor.putString("contentRating", MainAbility.contentRating); + Preferences editor = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + editor.putString("contentRating", MainAbility.getContentRating()); editor.flushSync(); TextField tagText = (TextField)findComponentById(ResourceTable.Id_tagsText); @@ -278,7 +274,7 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen TextField filterEdit = (TextField)findComponentById(ResourceTable.Id_filterText); config.filter = filterEdit.getText().toString(); Checkbox checkbox = (Checkbox)findComponentById(ResourceTable.Id_imagesCheckBox); - MainAbility.showImages = checkbox.isChecked(); + MainAbility.setShowImages(checkbox.isChecked()); config.type = getType(); @@ -286,9 +282,9 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen public StateElement setSelect() { StateElement stateElement = new StateElement(); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); return stateElement; } @@ -355,7 +351,7 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen BrowseConfig config = new BrowseConfig(); config.type = getType(); config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; + config.contentRating = MainAbility.getContentRating(); } @Override diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java index f74982ea2616e4eb7e4b5bd1f78e9fe4291119ef..e6b912b0cd163dcc9f54c5255035267b546bb78f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java @@ -27,7 +27,6 @@ import ohos.aafwk.ability.Ability; public class HttpChatAction extends HttpAction { ChatConfig config; - ChatResponse response; public HttpChatAction(Ability ability, ChatConfig config) { super(ability); @@ -37,7 +36,7 @@ public class HttpChatAction extends HttpAction { @Override protected String doInBackground(Void... params) { try { - this.response = MainAbility.connection.chat(this.config); + MainAbility.getConnection().chat(this.config); } catch (Exception exception) { this.exception = exception; } @@ -62,99 +61,6 @@ public class HttpChatAction extends HttpAction { return; } try { -// MainAbility.conversation = this.response.conversation; -// final ChatAbility Ability = (ChatAbility)this.ability; -// -// Image imageView = (Image)Ability.imageView; -// final VideoView videoView = Ability.videoView; -// Component videoLayout = Ability.videoLayout; -// -// if (MainAbility.sound && this.response.avatarActionAudio != null && this.response.avatarActionAudio.length() > 0) { -// // Action audio -// if (MainAbility.online) { -// Ability.playAudio(this.response.avatarActionAudio, false, true, true); -// } -// } -// if (MainAbility.sound && this.response.avatarAudio != null && this.response.avatarAudio.length() > 0) { -// Ability.music = true; -// // Background audio -// if (!this.response.avatarAudio.equals(Ability.currentAudio)) { -// if (Ability.audioPlayer != null) { -// Ability.audioPlayer.stop(); -// Ability.audioPlayer.release(); -// } -// if (MainAbility.online) { -// Ability.audioPlayer = Ability.playAudio(this.response.avatarAudio, true, true, true); -// } -// //making sure the that mic is turned off while using the DeviceVoice. -// ChatAbility.micLastStat = false; -// } -// } else if (Ability.audioPlayer != null) { -// Ability.audioPlayer.stop(); -// Ability.audioPlayer.release(); -// Ability.audioPlayer = null; -// Ability.music = false; -// } -// -// if (!MainAbility.disableVideo && !Ability.videoError && this.response.isVideo()) { -// // Video avatar -// if (imageView.getVisibility() != View.GONE || videoLayout.getVisibility() != View.GONE) { -// if (imageView.getVisibility() == View.VISIBLE) { -// imageView.setVisibility(View.GONE); -// } -// if (videoLayout.getVisibility() == View.GONE) { -// videoLayout.setVisibility(View.VISIBLE); -// } -// } -// if (this.response.avatarAction != null && this.response.avatarAction.length() > 0) { -// // Action video -// videoView.setOnPreparedListener(new OnPreparedListener() { -// @Override -// public void onPrepared(MediaPlayer mp) { -// mp.setLooping(false); -// } -// }); -// videoView.setOnCompletionListener(new OnCompletionListener() { -// @Override -// public void onCompletion(MediaPlayer mp) { -// Ability.resetVideoErrorListener(); -// videoView.setOnCompletionListener(null); -// Ability.cycleVideo(response); -// Ability.response(response); -// } -// }); -// videoView.setOnErrorListener(new OnErrorListener() { -// @Override -// public boolean onError(MediaPlayer mp, int what, int extra) { -// Ability.resetVideoErrorListener(); -// Ability.cycleVideo(response); -// Ability.response(response); -// return true; -// } -// }); -// Ability.playVideo(this.response.avatarAction, false); -// return; -// } else { -// Ability.cycleVideo(this.response); -// } -// } else { -// // Image avatar -// if (imageView.getVisibility() != View.GONE || videoLayout.getVisibility() != View.GONE) { -// if (imageView.getVisibility() == View.GONE) { -// imageView.setVisibility(View.VISIBLE); -// } -// if (videoLayout.getVisibility() == View.VISIBLE) { -// videoLayout.setVisibility(View.GONE); -// } -// } -// if (this.response.isVideo()) { -// HttpGetImageAction.fetchImage(this.ability, ((ChatAbility)this.ability).getAvatarIcon(this.response), imageView); -// } else { -// HttpGetImageAction.fetchImage(this.ability, this.response.avatar, imageView); -// } -// } -// -// Ability.response(this.response); } catch (Exception error) { this.exception = error; MainAbility.error(this.exception.getMessage(), this.exception, this.ability); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java index dd3efc61703b320507273886cd2cc06efa6ad289..36a291a302a9e89cd7c2d4decb7133f33ec9e49d 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java @@ -40,7 +40,7 @@ public class HttpConnectAction extends HttpUIResultAction { public void doInBackground() { loadingDialog(); try { - this.config = MainAbility.connection.connect(config); + this.config = MainAbility.getConnection().connect(config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -55,7 +55,7 @@ public class HttpConnectAction extends HttpUIResultAction { return; } try { - MainAbility.user = this.config; + MainAbility.setUser(this.config); if (this.ability instanceof MainAbility) { ((MainAbility) this.ability).resetView(); } @@ -63,8 +63,8 @@ public class HttpConnectAction extends HttpUIResultAction { if (this.finish) { Preferences cookies = PreferencesUtils.getPreferences(ability); - cookies.putString("user", MainAbility.user.user); - cookies.putString("token", MainAbility.user.token); + cookies.putString("user", MainAbility.getUser().user); + cookies.putString("token", MainAbility.getUser().token); cookies.flushSync(); this.ability.terminateAbility(); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java index 07ab9d620cf25e2d854134a7a68e484704c519c4..084535d7998c8b94886f9d8b5c31cce2ad930884 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java @@ -44,7 +44,7 @@ public class HttpCreateAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.config = MainAbility.connection.create(this.config); + this.config = MainAbility.getConnection().create(this.config); } catch (Exception exception) { this.exception = exception; } @@ -59,7 +59,7 @@ public class HttpCreateAction extends HttpUIAction { return; } try { - MainAbility.instance = this.config; + MainAbility.setInstance(this.config); if (this.finish) { this.ability.terminateAbility(); @@ -68,10 +68,6 @@ public class HttpCreateAction extends HttpUIAction { Preferences cookies= PreferencesUtils.getPreferences(this.ability); cookies.putString(this.config.getType(), this.config.name); cookies.flushSync(); - -// Class childAbility = MainAbility.getAbility(this.config); -// startOpenAbility(this.ability,childAbility.getName()); - } catch (Exception error) { this.exception = error; MainAbility.error(this.exception.getMessage(), this.exception, this.ability); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java index 18ff0673a175067bbddea811b127bb7fe77e792a..2c87b7ea62677287e8f72f99f259e9ed9c4254e7 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java @@ -27,19 +27,16 @@ import ohos.app.Context; public class HttpCreateUserAction extends HttpUIResultAction { UserConfig config; - private Context context; public HttpCreateUserAction(Context context, Ability ability, UserConfig config) { super(ability); this.config = config; - this.context = context; doInBackground(); } -// @Override protected void doInBackground() { try { - this.config = MainAbility.connection.create(ability,this.config); + this.config = MainAbility.getConnection().create(ability,this.config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -50,7 +47,7 @@ public class HttpCreateUserAction extends HttpUIResultAction { return; } try { - MainAbility.user = this.config; + MainAbility.setUser(this.config); this.ability.terminateAbility(); } catch (Exception error) { this.exception = error; diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java index 95326648f8a83ea11929adca6713de8da43a96df..3a6ca3301bc51e8b5e0456a513a95d236d49479a 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java @@ -29,111 +29,83 @@ import org.botlibre.sdk.config.InstanceConfig; import org.botlibre.sdk.config.WebMediumConfig; import org.botlibre.sdk.util.PreferencesUtils; +import static org.botlibre.sdk.MainAbility.*; + public class HttpFetchAction extends HttpUIResultAction { - WebMediumConfig config; - boolean launch; + WebMediumConfig config; + boolean launch; - public HttpFetchAction(Ability ability, WebMediumConfig config) { - super(ability); - this.config = config; - } - - public HttpFetchAction(Ability ability, WebMediumConfig config, boolean launch) { - super(ability); - this.config = config; - this.launch = launch; - doInBackground(); - } + public HttpFetchAction(Ability ability, WebMediumConfig config) { + super(ability); + this.config = config; + } - public void doInBackground(){ - loadingDialog(); - try { - this.config = MainAbility.connection.fetch(this.config); - } catch (Exception exception) { - this.exception = exception; - removeDialog(); - return; - } - onPostExecute(); - } + public HttpFetchAction(Ability ability, WebMediumConfig config, boolean launch) { + super(ability); + this.config = config; + this.launch = launch; + doInBackground(); + } -// @Override -// protected String doInBackground(Void... params) { -// try { -// -// } catch (Exception exception) { -// this.exception = exception; -// } -// return ""; -// } - -// public void superOnPostExecute(String xml) { -// super.onPostExecute(xml); -// } + public void doInBackground() { + loadingDialog(); + try { + this.config = getConnection().fetch(this.config); + } catch (Exception exception) { + this.exception = exception; + removeDialog(); + return; + } + onPostExecute(); + } - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") // @Override - public void onPostExecute() { -// super.onPostExecute(xml); - if (this.exception != null) { - return; - } - try { - MainAbility.instance = this.config; + public void onPostExecute() { + if (this.exception != null) { + return; + } + try { + setInstance(this.config); + + Preferences cookies = PreferencesUtils.getPreferences(this.ability); + cookies.putString(this.config.getType(), this.config.name); + cookies.flushSync(); + + Class childAbility = getAbility(this.config); + if (this.launch && !this.config.isExternal) { + if (this.config instanceof ChannelConfig) { + } else if (this.config instanceof InstanceConfig) { + } else if (this.config instanceof DomainConfig) { + getConnection().setDomain((DomainConfig) this.config); + setDomain((DomainConfig) this.config); + setForumCategories(null); + setChannelTags(null); + setChannelCategories(null); + setDomainTags(null); + setDomainCategories(null); + setGraphicTags(null); + setGraphicCategories(null); - Preferences cookies= PreferencesUtils.getPreferences(this.ability); - cookies.putString(this.config.getType(), this.config.name); - cookies.flushSync(); + setType(getDefaultType()); + startOpenAbility(this.ability, MainAbility.class.getName()); + return; + } else if (this.config instanceof ForumConfig) { + BrowseConfig config = new BrowseConfig(); - Class childAbility = MainAbility.getAbility(this.config); - if (this.launch && !this.config.isExternal) { - if (this.config instanceof ChannelConfig) { -// childAbility = LiveChatAbility.class; - } else if (this.config instanceof InstanceConfig) { -// childAbility = ChatAbility.class; - } else if (this.config instanceof DomainConfig) { - MainAbility.connection.setDomain((DomainConfig)this.config); - MainAbility.domain = (DomainConfig)this.config; - MainAbility.tags = null; - MainAbility.categories = null; - MainAbility.forumTags = null; - MainAbility.forumCategories = null; - MainAbility.channelTags = null; - MainAbility.channelCategories = null; - MainAbility.domainTags=null; - MainAbility.domainCategories=null; - MainAbility.graphicTags = null; - MainAbility.graphicCategories = null; - - MainAbility.type = MainAbility.defaultType; -// Intent intent = new Intent(this.ability, MainAbility.class); -// intent.setFlags(Intent.FLAG_Ability_NEW_TASK); -// intent.setFlags(Intent.FLAG_Ability_CLEAR_TOP); -// this.ability.startAbility(intent); - startOpenAbility(this.ability,MainAbility.class.getName()); - return; - } else if (this.config instanceof ForumConfig) { - BrowseConfig config = new BrowseConfig(); - - config.typeFilter = "Public"; - config.type = "Post"; - config.instance = MainAbility.instance.id; - config.sort = "date"; + config.typeFilter = "Public"; + config.type = "Post"; + config.instance = getInstance().id; + config.sort = "date"; + return; + } + } + startOpenAbility(this.ability, childAbility.getName()); + } catch (Exception error) { + this.exception = error; + error(this.exception.getMessage(), this.exception, this.ability); + return; + } + } - HttpGetPostsAction action = new HttpGetPostsAction(this.ability, config); -// action.execute(); - return; - } - } else { - if (this.config instanceof InstanceConfig) { - } - } - startOpenAbility(this.ability,childAbility.getName()); - } catch (Exception error) { - this.exception = error; - MainAbility.error(this.exception.getMessage(), this.exception, this.ability); - return; - } - } - } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchActionOffline.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchActionOffline.java index 0b4184667f3c80298db345f0e82c56322da3f722..1519aa83a694cc0b4a266bc24934c491ffc4580f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchActionOffline.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchActionOffline.java @@ -77,7 +77,7 @@ public class HttpFetchActionOffline extends HttpUIAction { try { //switch connections. MainAbility.setOnline(false); - microConnection = (MicroConnection) MainAbility.connection; + microConnection = (MicroConnection) MainAbility.getConnection(); this.config = microConnection.fetch(this.config); } catch (Exception exception) { this.exception = exception; @@ -92,7 +92,7 @@ public class HttpFetchActionOffline extends HttpUIAction { return ""; } try { - MainAbility.instance = this.config; + MainAbility.setInstance(this.config); Class childAbility = MainAbility.getAbility(this.config); if (this.launch && !this.config.isExternal) { if (this.config instanceof InstanceConfig) { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java index fa0b984363739d8ad83de0e2db0f4b0312d6a1ed..f3e80d6bbbd59ae052f6b03e71866a796a2ea9dc 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java @@ -32,7 +32,7 @@ public class HttpFetchChatAvatarAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.config = MainAbility.connection.fetch(this.config); + this.config = MainAbility.getConnection().fetch(this.config); } catch (Exception exception) { this.exception = exception; } @@ -46,7 +46,6 @@ public class HttpFetchChatAvatarAction extends HttpUIAction { return; } try { -// ((ChatAbility)this.ability).resetAvatar(this.config); } catch (Exception error) { this.exception = error; MainAbility.error(this.exception.getMessage(), this.exception, this.ability); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagIssueAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagIssueAction.java index 1accaa47641a1ff71684b3ddffbe7b2aff3b1294..57525bdd11cf31d152a6c92bcb6d691660048e2a 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagIssueAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagIssueAction.java @@ -33,7 +33,7 @@ public class HttpFlagIssueAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - MainAbility.connection.flag(this.config); + MainAbility.getConnection().flag(this.config); } catch (Exception exception) { this.exception = exception; } @@ -46,7 +46,6 @@ public class HttpFlagIssueAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.issue.isFlagged = true; -// this.ability.findComponentById(ResourceTable.flaggedLabel).setVisibility(VISIBLE); + MainAbility.getIssue().isFlagged = true; } } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java index 6222aeb7081223e23c9b016988fd98557e0e34ea..79884ce2db786e71910c2f966318bb1053dfed18 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java @@ -32,7 +32,7 @@ public class HttpFlagUserAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - MainAbility.connection.flag(this.config); + MainAbility.getConnection().flag(this.config); } catch (Exception exception) { this.exception = exception; } @@ -45,8 +45,6 @@ public class HttpFlagUserAction extends HttpUIAction { if (this.exception != null) { return; } - //MainAbility.viewUser.isFlagged = true; - //this.Ability.findViewById(R.id.flaggedLabel).setVisibility(View.VISIBLE); } } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java index d9eb94280adbd2a4b22908c51895ae16ff014009..9efe353bea2f70148c3dc8e624275901db760bdb 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java @@ -30,7 +30,6 @@ public class HttpGetInstancesAction extends HttpUIResultAction { BrowseConfig config; List instances; boolean finish = false; - boolean CustomAvatar = false; public HttpGetInstancesAction(Ability ability, BrowseConfig config) { super(ability); @@ -49,13 +48,12 @@ public class HttpGetInstancesAction extends HttpUIResultAction { super(ability); this.config = config; this.finish = finish; - this.CustomAvatar = CustomAvatar; } public void doInBackground(){ loadingDialog(); try { - this.instances = MainAbility.connection.browse(ability,config); + this.instances = MainAbility.getConnection().browse(ability,config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -76,7 +74,7 @@ public class HttpGetInstancesAction extends HttpUIResultAction { if (this.exception != null) { return; } - MainAbility.instances = this.instances; + MainAbility.setInstances(this.instances); if (this.finish) { this.ability.terminateAbility(); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java index 09f2164cca848c27379a0ee2fcad425fd34291e4..7b9ca7d7eceb7809ce98f7965f2b5fdaa9b9f88f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java @@ -46,7 +46,7 @@ public class HttpGetPostsAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.posts = MainAbility.connection.getPosts(this.config); + this.posts = MainAbility.getConnection().getPosts(this.config); } catch (Exception exception) { this.exception = exception; } @@ -59,19 +59,13 @@ public class HttpGetPostsAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.posts = this.posts; + MainAbility.setPosts(this.posts); if (this.finish) { this.ability.terminateAbility(); } - MainAbility.browsePosts = this.config; + MainAbility.setBrowsePosts(this.config); Intent intent = new Intent(); -// Operation operation = new Intent.OperationBuilder() -// .withDeviceId("") -// .withBundleName(this.ability.getBundleName()) -// .withAbilityName(BrowsePostAbility.class.getName()) -// .build(); -// intent.setOperation(operation); this.ability.startAbility(intent); } } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java index 6b6e5f7a5b4508551fdbe969d3169da9981da5e5..080dc7224630bed29ff45bba2fec7a09194a629e 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java @@ -26,7 +26,6 @@ import ohos.agp.components.Text; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerAdapter extends BaseItemProvider { @@ -38,11 +37,11 @@ public class SpinnerAdapter extends BaseItemProvider { * 构造函数 * * @param ability ability - * @param types types + * @param types types */ public SpinnerAdapter(Ability ability, String[] types) { mAbility = ability; - this.types = types; + this.types = types.clone(); mInflater = LayoutScatter.getInstance(ability); } @@ -84,15 +83,14 @@ public class SpinnerAdapter extends BaseItemProvider { /** * getComponent * - * @param position position - * @param component1 component1 + * @param position position + * @param component component1 * @param componentContainer componentContainer * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; if (component == null) { component = mInflater.parse(ResourceTable.Layout_simple_spinner_dropdown_item, componentContainer, false); @@ -109,7 +107,6 @@ public class SpinnerAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java index a75ead36800635748095bc8f89239222aa9e7517..89f91d097cfe268c52dd02ebb1ea335763a9c482 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java @@ -42,7 +42,6 @@ public class AvatarSelection extends Ability { final int [] imges = {}; final String [] names = {}; ((Text) findComponentById(ResourceTable.Id_theTitle)).setText("Select Avatar"); - final ListContainer listView = (ListContainer) findComponentById(ResourceTable.Id_theListView); ArrayList items = new ArrayList(); for (int i = 0; i < names.length; i++) { items.add(new OfflineTemplateConfig(imges[i],names[i],null,null)); @@ -51,8 +50,8 @@ public class AvatarSelection extends Ability { } public static void saveSelectedAvatar(String nameOfAvatar) { - MainAbility.nameOfAvatar = nameOfAvatar; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); + MainAbility.setNameOfAvatar(nameOfAvatar); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); cookies.putString("nameOfAvatar", nameOfAvatar); cookies.flushSync(); } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java index b14752da2ad09c11c8ac78699949724ab1af4531..53b2e35a54946f4423d193ec29a3f80f3502c7e1 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 语言对话框 * - * @author BotLibre * @since 2021-05-10 */ public class LanguageDialogBuilder { @@ -75,13 +74,13 @@ public class LanguageDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.languages); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getLanguages()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer list, Component component, int ii, long ll) { - MainAbility.selectInfo = MainAbility.languages[ii]; // 赋值 选择的选项 - selectListener.selectLanguageItem(MainAbility.languages[ii] + ""); + MainAbility.setSelectInfo(MainAbility.getLanguages()[ii]); // 赋值 选择的选项 + selectListener.selectLanguageItem(MainAbility.getLanguages()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java index 34c67053c103c3e2a87c24dca243287ed1c7ee15..2a575710711b1ba6da83d91e8c2c3447e9ad8d2d 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java @@ -35,7 +35,6 @@ import java.util.Optional; /** * 搜索对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SearchDialogBuilder { @@ -51,7 +50,7 @@ public class SearchDialogBuilder { * @param spinStr spinStr */ public SearchDialogBuilder(Ability context,String[] spinStr) { - this.spinStr = spinStr; + this.spinStr = spinStr.clone(); initLayout(context); } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java index d8caef1fa97f65a4d41c50e0c281907e74135f3d..30962a3c1db6da45daa68f8bbc8e25cbcddd8582 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerDialogBuilder { @@ -75,13 +74,13 @@ public class SpinnerDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.types); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getTypes()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer listCon, Component component, int ii, long ll) { - MainAbility.type = MainAbility.types[ii]; // 赋值 选择的选项 - selectListener.selectItem(MainAbility.types[ii] + ""); + MainAbility.setType(MainAbility.getTypes()[ii]); // 赋值 选择的选项 + selectListener.selectItem(MainAbility.getTypes()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java index 1c0419f9a72e8569c22923923a87c3b55b740012..11be68b73ff1b71ce94664e4f9aef3144c07623f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java @@ -18,7 +18,7 @@ public class HttpChatWarAction extends HttpUIAction { protected String doInBackground(Void... params) { try { InstanceConfig instance = new InstanceConfig(); - this.instance = (InstanceConfig) MainAbility.connection.custom("chat-war", this.config, instance); + this.instance = (InstanceConfig) MainAbility.getConnection().custom("chat-war", this.config, instance); } catch (Exception exception) { this.exception = exception; } @@ -31,7 +31,7 @@ public class HttpChatWarAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.instance = this.instance; + MainAbility.setInstance(this.instance); } } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java index d73f2ead779026677178b1fdf82bdb1de7925585..a0caaf3abc0383306b86a5f45b8954151a5e4a68 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java @@ -41,153 +41,128 @@ import java.util.List; * Ability for user login. */ public class StartWarAbility extends LibreAbility implements Component.ClickedListener { - protected int browsing = 0; - public static InstanceConfig winner; - public static InstanceConfig looser; - public static InstanceConfig bot1; - public static InstanceConfig bot2; - public static String topic = "Hello"; - public boolean handsFreeSpeechWAS; - - private static long SECRET = 4357845875643L; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_start_war); - if(MainAbility.handsFreeSpeech) { - handsFreeSpeechWAS = true; - MainAbility.handsFreeSpeech = false; - } - - ((TextField)findComponentById(ResourceTable.Id_topicText)).setText(topic); + protected int browsing = 0; + public InstanceConfig winner; + public InstanceConfig looser; + public InstanceConfig bot1; + public InstanceConfig bot2; + public String topic = "Hello"; + public boolean handsFreeSpeechWAS; + + private static long SECRET = 4357845875643L; + + @Override + public void onStart(Intent intent) { + super.onStart(intent); + super.setUIContent(ResourceTable.Layout_ability_start_war); + if (MainAbility.isHandsFreeSpeech()) { + handsFreeSpeechWAS = true; + MainAbility.setHandsFreeSpeech(false); + } + + ((TextField) findComponentById(ResourceTable.Id_topicText)).setText(topic); winner = null; looser = null; - - if (bot1 == null) { - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - String last = cookies.getString("instance", null); - if (last != null && !last.isEmpty()) { - InstanceConfig config = new InstanceConfig(); - config.name = last; - HttpFetchWarAction action = new HttpFetchWarAction(this, config); -// action.execute(); - } - } - - MainAbility.connection.setUser(MainAbility.user); - if (MainAbility.browsing) { - if ((MainAbility.instance instanceof InstanceConfig)) { - if (this.browsing == 0) { - bot1 = (InstanceConfig)MainAbility.instance; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - cookies.putString(bot1.getType(), bot1.name); - cookies.flushSync(); - } else { - bot2 = (InstanceConfig)MainAbility.instance; - } - } - } else if (winner != null) { - try{ - String text = "Last war " + winner.name + " beat " + looser.name + "."; - ((Text)findComponentById(ResourceTable.Id_winner)).setText(text); - ChatWarConfig config = new ChatWarConfig(); - config.winner = winner.id; - config.looser = looser.id; - config.topic = topic; - config.secret = String.valueOf(SECRET + MainAbility.user.user.length()); - HttpChatWarAction action = new HttpChatWarAction(this, config); - action.execute(); - }catch(Exception e){ - MainAbility.showMessage("You must be signed in to vote!", this); - } - } - MainAbility.browsing = false; - resetView(); - } - - public void resetView() { - try{ - List instances = new ArrayList(); - if (bot1 != null) { - instances.add(bot1); - } -// ListContainer list = (ListContainer) findComponentById(ResourceTable.Id_bot1List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); -// instances = new ArrayList(); -// if (bot2 != null) { -// instances.add(bot2); -// } -// list = (ListContainer) findComponentById(ResourceTable.Id_bot2List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); - }catch(Exception e){ - } - - Button warButton = (Button)findComponentById(ResourceTable.Id_warButton); - warButton.setClickedListener(this); - Button bot2Button = (Button)findComponentById(ResourceTable.Id_bot2Button); - bot2Button.setClickedListener(this); - Button bot1Button = (Button)findComponentById(ResourceTable.Id_bot1Button); - bot1Button.setClickedListener(this); - } - - /** - * Start a new war. - */ - public void war() { + + if (bot1 == null) { + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + String last = cookies.getString("instance", null); + if (last != null && !last.isEmpty()) { + InstanceConfig config = new InstanceConfig(); + config.name = last; + } + } + + MainAbility.getConnection().setUser(MainAbility.getUser()); + if (MainAbility.isBrowsing()) { + if ((MainAbility.getInstance() instanceof InstanceConfig)) { + if (this.browsing == 0) { + bot1 = (InstanceConfig) MainAbility.getInstance(); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + cookies.putString(bot1.getType(), bot1.name); + cookies.flushSync(); + } else { + bot2 = (InstanceConfig) MainAbility.getInstance(); + } + } + } + MainAbility.setBrowsing(false); + resetView(); + } + + public void resetView() { + try { + List instances = new ArrayList(); + if (bot1 != null) { + instances.add(bot1); + } + } catch (Exception e) { + } + + Button warButton = (Button) findComponentById(ResourceTable.Id_warButton); + warButton.setClickedListener(this); + Button bot2Button = (Button) findComponentById(ResourceTable.Id_bot2Button); + bot2Button.setClickedListener(this); + Button bot1Button = (Button) findComponentById(ResourceTable.Id_bot1Button); + bot1Button.setClickedListener(this); + } + + /** + * Start a new war. + */ + public void war() { if (bot1 == null || bot2 == null) { - MainAbility.showMessage("Please select two bots to start a war", this); - return; + MainAbility.showMessage("Please select two bots to start a war", this); + return; } - topic = ((TextField)findComponentById(ResourceTable.Id_topicText)).getText().toString(); + topic = ((TextField) findComponentById(ResourceTable.Id_topicText)).getText().toString(); if (topic == null || topic.isEmpty()) { - MainAbility.showMessage("Please enter a topic", this); - return; + MainAbility.showMessage("Please enter a topic", this); + return; } - MainAbility.instance = bot1; - MainAbility.connection.setUser(null); -// startOpenAbility(this,WarAbility.class.getName()); + MainAbility.setInstance( bot1); + MainAbility.getConnection().setUser(null); } - public void browseBot1() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - this.browsing = 0; - } - - public void browseBot2() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - MainAbility.instance = null; - this.browsing = 1; - } - - @Override - protected void onBackground() { - if(handsFreeSpeechWAS){ - MainAbility.handsFreeSpeech = true; - } - super.onBackground(); - } - - @Override - public void onClick(Component component) { - if(component.getId() == ResourceTable.Id_warButton){ - war(); - } - if(component.getId() == ResourceTable.Id_bot1Button){ - browseBot1(); - } - if(component.getId() == ResourceTable.Id_bot2Button){ - browseBot2(); - } - } + public void browseBot1() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(true); + this.browsing = 0; + } + + public void browseBot2() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(false); + MainAbility.setInstance(null); + this.browsing = 1; + } + + @Override + protected void onBackground() { + if (handsFreeSpeechWAS) { + MainAbility.setHandsFreeSpeech(true); + } + super.onBackground(); + } + + @Override + public void onClick(Component component) { + if (component.getId() == ResourceTable.Id_warButton) { + war(); + } + if (component.getId() == ResourceTable.Id_bot1Button) { + browseBot1(); + } + if (component.getId() == ResourceTable.Id_bot2Button) { + browseBot2(); + } + } } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java index d37dd0797d08c1d2da7ea52d7fa1fb4058425d3c..6ee4b1e8e5b09020b632529ee2fda76bdfaaba29 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java @@ -1,21 +1,3 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.config; import java.io.StringWriter; @@ -31,7 +13,7 @@ import org.w3c.dom.Element; public class AvatarMedia extends Config { public String mediaId; public String name; - public String type; + public String types; public String media; public String emotions; public String actions; @@ -44,7 +26,7 @@ public class AvatarMedia extends Config { this.mediaId = element.getAttribute("mediaId"); this.name = element.getAttribute("name"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.media = element.getAttribute("media"); this.emotions = element.getAttribute("emotions"); this.actions = element.getAttribute("actions"); @@ -85,18 +67,18 @@ public class AvatarMedia extends Config { return hd; } public boolean isImage() { - return this.type.contains("image") || this.type.isEmpty(); + return this.types.contains("image") || this.type.isEmpty(); } public boolean isVideo() { - return this.type != null && this.type.indexOf("video") != -1; + return this.types != null && this.type.indexOf("video") != -1; } public boolean isAudio() { - return this.type != null && this.type.indexOf("audio") != -1; + return this.types != null && this.type.indexOf("audio") != -1; } public String getType() { - return type; + return types; } public String getEmotions() { return emotions; diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java index 992215f546b61796584a2dad19948c43847f057b..e108292f5baab85d59242595efd0896d986a6269 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java @@ -1,21 +1,3 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.config; import java.io.StringWriter; @@ -24,7 +6,7 @@ import java.io.StringWriter; * DTO for XML browse options. */ public class BrowseConfig extends Config { - public String type; + public String types; public String typeFilter; public String category; public String tag; @@ -39,7 +21,7 @@ public class BrowseConfig extends Config { StringWriter writer = new StringWriter(); writer.write(""); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java index dc2b363caa5cdff7ea26f35508506ccabf8f9c72..b61bbca4a522a5dd0fb5ba96e6c2eeaf90fec807 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java @@ -1,21 +1,3 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.config; import java.text.SimpleDateFormat; @@ -35,14 +17,14 @@ import org.w3c.dom.NodeList; public class ConversationConfig extends Config { public String id; public String creationDate; - public String type; + public String types; public List input; public void parseXML(Element element) { this.id = element.getAttribute("id"); this.creationDate = element.getAttribute("creationDate"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); NodeList nodes = element.getElementsByTagName("input"); if (nodes != null && nodes.getLength() > 0) { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java index 50ed66a264cf38d85254c5d1ab3390b0a1ed6788..e8133daa45b816ee85ca962bbdbf03dd1fec28b6 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.Objects; import org.botlibre.sdk.util.Utils; import org.w3c.dom.Element; @@ -69,7 +70,12 @@ public class ForumPostConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, topic, summary, details, detailsText, forum, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isFeatured, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, replyCount, parent, avatar, replies); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java index a706bfb66db5664425fea2d3940d01fe3154768b..014f21dd000859d3ba1e03707161a5e73b821d6e 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java @@ -27,6 +27,7 @@ import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; /** @@ -65,7 +66,12 @@ public class IssueConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, title, priority, summary, details, detailsText, tracker, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isPriority, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, avatar); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java index 3237a0a40ffdeff201f2f67b22c0333050e02d21..cb8e98b56611e49058e5e42b5222ce3595fcb00e 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java @@ -1,21 +1,3 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.config; import java.io.StringWriter; @@ -29,7 +11,7 @@ import org.w3c.dom.Element; public class MediaConfig extends Config { public long id; public String name; - public String type; + public String types; public String file; public String key; @@ -38,7 +20,7 @@ public class MediaConfig extends Config { this.id = Long.valueOf(element.getAttribute("id")); this.name = element.getAttribute("name"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.file = element.getAttribute("file"); this.key = element.getAttribute("key"); } @@ -56,7 +38,7 @@ public class MediaConfig extends Config { writer.write(" name=\"" + this.name + "\""); } if (this.type != null) { - writer.write(" type=\"" + this.type + "\""); + writer.write(" type=\"" + this.types + "\""); } if (this.file != null) { writer.write(" file=\"" + this.file + "\""); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java index e0963e48207c8c00f6e5824e34d511d1bb8f2469..bf74806b009d1bb46c59b47e6fda23172871cfaf 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java @@ -19,6 +19,7 @@ package org.botlibre.sdk.config; import java.io.StringWriter; +import java.util.Objects; import ohos.utils.zson.ZSONException; import ohos.utils.zson.ZSONObject; @@ -73,6 +74,11 @@ public class ResponseConfig extends Config { return super.equals(object); } + @Override + public int hashCode() { + return Objects.hash(questionId, responseId, question, response, previous, onRepeat, label, topic, keywords, required, emotions, actions, poses, noRepeat, requirePrevious, requireTopic, flagged, correctness, command); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java index 6e2324f4aab4c99d82c91c539df79ba343f37f9b..d7261184b8cc0050998991947f00b838590854d8 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java @@ -1,27 +1,10 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - package org.botlibre.sdk.config; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; import org.botlibre.sdk.SDKConnection; import org.w3c.dom.Element; @@ -57,7 +40,7 @@ public class UserConfig extends Config { public String joined; public String lastConnect; - public String type; + public String types; public boolean isFlagged; public String flaggedReason; @@ -98,6 +81,11 @@ public class UserConfig extends Config { return this.user != null && this.user.equals(((UserConfig)object).user); } + @Override + public int hashCode() { + return Objects.hash(password, newPassword, hint, name, showName, email, website, bio, over18, avatar, connects, bots, posts, messages, forums, scripts, graphics, avatars, domains, channels, joined, lastConnect, type, isFlagged, flaggedReason); + } + public void parseXML(Element element) { this.user = element.getAttribute("user"); this.name = element.getAttribute("name"); @@ -118,7 +106,7 @@ public class UserConfig extends Config { this.domains = element.getAttribute("domains"); this.joined = element.getAttribute("joined"); this.lastConnect = element.getAttribute("lastConnect"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.isFlagged = Boolean.valueOf(element.getAttribute("isFlagged")); Node node = element.getElementsByTagName("bio").item(0); diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/BootstrapAsync.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/BootstrapAsync.java deleted file mode 100644 index 5c8e4d83fc0b8525af07dec03f739936e6d02f8f..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/BootstrapAsync.java +++ /dev/null @@ -1,193 +0,0 @@ -package org.botlibre.sdk.micro; - -import org.botlibre.sdk.MainAbility; -import org.botlibre.sdk.ability.actions.HttpUIAction; -import org.botlibre.sdk.config.InstanceConfig; -import org.botlibre.sdk.config.ScriptConfig; -import org.botlibre.sdk.config.ScriptSourceConfig; -import org.botlibre.sdk.util.PreferencesUtils; -import ohos.aafwk.ability.Ability; -import ohos.data.preferences.Preferences; -import org.botlibre.Bot; -import org.botlibre.api.knowledge.Network; -import org.botlibre.api.knowledge.Vertex; -import org.botlibre.api.sense.Sense; -import org.botlibre.knowledge.Bootstrap; -import org.botlibre.knowledge.Primitive; -import org.botlibre.knowledge.micro.MicroMemory; -import org.botlibre.self.SelfCompiler; -import org.botlibre.sense.http.Wiktionary; -import org.botlibre.sense.text.TextEntry; -import org.botlibre.thought.consciousness.Consciousness; -import org.botlibre.thought.language.Comprehension; -import org.botlibre.thought.language.Language; -import org.botlibre.thought.language.Language.LearningMode; - -/** - * Bootstrap the bot the first time from an online response list file or script. - */ -public class BootstrapAsync extends HttpUIAction { - public BootstrapAsync(Ability Ability) { - super(Ability); - } - - protected String aimlScriptId; - protected String selfScriptId; - protected String greetingScriptId; - InstanceConfig config; - MicroConnection connection; - Bot bot=null; - boolean noInternet = false; - - //passing InstanceConfig and the Scripts Versions. - public synchronized void bootstrapBot(InstanceConfig config, String aimlScriptId, String greetingScriptId) { - this.greetingScriptId = greetingScriptId; - this.aimlScriptId = aimlScriptId; - this.config = config; - this.execute(); - } - - protected boolean isResetRequired() { - // Check if bot memory exists. - if (!MicroMemory.checkExists()) { - return true; - } - try{ - // Check if version is changed. - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - String aimlVersion = cookies.getString(this.aimlScriptId, null); - String greetingVersion = cookies.getString(this.greetingScriptId, null); - if (aimlVersion == null || aimlVersion.isEmpty() || greetingVersion == null || greetingVersion.isEmpty()) { - return true; - } - ScriptConfig aimlScript = new ScriptConfig(); - aimlScript.id = this.aimlScriptId; - aimlScript = MainAbility.connection.fetch(aimlScript); - if (!aimlVersion.equals(aimlScript.version)) { - return true; - } - ScriptConfig greetingScript = new ScriptConfig(); - greetingScript.id = this.greetingScriptId; - greetingScript = MainAbility.connection.fetch(greetingScript); - if (!greetingVersion.equals(greetingScript.version)) { - return true; - } - } catch (Exception ignore) { - return false; - } - return false; - } - - @Override - protected String doInBackground(Void... params) { - try { - MicroMemory.storageFileName = this.config.id; - this.connection = (MicroConnection) MainAbility.connection; - // Check if bot is already loaded first. - if (connection.getBot(this.config.id) != null) { - return ""; - } - // Check if bot memory exists. - boolean resetRequired = isResetRequired(); - - // If no reset is required, just load the bot. - if (!resetRequired) { - try { - this.bot = Bot.createInstance(Bot.CONFIG_FILE, this.config.id, true); - Language language = bot.mind().getThought(Language.class); - language.setLearningMode(LearningMode.Disabled); - language.setLearnGrammar(false); - Comprehension comprehension = bot.mind().getThought(Comprehension.class); - comprehension.setEnabled(false); - Consciousness consciousness = bot.mind().getThought(Consciousness.class); - consciousness.setEnabled(false); - Sense sense = bot.awareness().getSense(Wiktionary.class); - sense.setIsEnabled(false); - } catch (Exception failed) { - // If the load fails, then reset the bot. - resetRequired = true; - } - } - // If a reset is required the bot must be rebuilt from scratch and reimport the AIML and greeting files. - if (resetRequired) { - // Delete the old file if exists. - MicroMemory.reset(); - // Fetch the scripts source code. - ScriptConfig aimlScript = new ScriptConfig(); - aimlScript.id = this.aimlScriptId; - ScriptSourceConfig aimlSource = connection.getScriptSource(aimlScript); - ScriptConfig greetingScript = new ScriptConfig(); - greetingScript.id = this.greetingScriptId; - ScriptSourceConfig greetingSource = connection.getScriptSource(greetingScript); - - MicroMemory.reset(); - // Create new bot. - bot = Bot.createInstance(Bot.CONFIG_FILE, this.config.id, true); - Language language = bot.mind().getThought(Language.class); - language.setLearningMode(LearningMode.Disabled); - language.setLearnGrammar(false); - Comprehension comprehension = bot.mind().getThought(Comprehension.class); - comprehension.setEnabled(false); - Consciousness consciousness = bot.mind().getThought(Consciousness.class); - consciousness.setEnabled(false); - Sense sense = bot.awareness().getSense(Wiktionary.class); - sense.setIsEnabled(false); - //if bootstrapSystem was true, it will load the default script. - // Do not need to bootstrap, as only uses AIML. - new Bootstrap().bootstrapSystem(bot, false); - // Load AIML file. - language.loadAIML(aimlSource.source, "ami", true, false, false); - // Load greeting response list. - bot.awareness().getSense(TextEntry.class).loadChat(greetingSource.source, "Response List", false, true); - - // Shutdown will save the file. - bot.shutdown(); - // Reload the bot from the file. - bot = Bot.createInstance(Bot.CONFIG_FILE, this.config.id, true); - language = bot.mind().getThought(Language.class); - language.setLearningMode(LearningMode.Disabled); - language.setLearnGrammar(false); - comprehension = bot.mind().getThought(Comprehension.class); - comprehension.setEnabled(false); - consciousness = bot.mind().getThought(Consciousness.class); - consciousness.setEnabled(false); - sense = bot.awareness().getSense(Wiktionary.class); - sense.setIsEnabled(false); - - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - cookies.putString(this.aimlScriptId, aimlSource.versionName); - cookies.putString(this.greetingScriptId, greetingSource.versionName); - cookies.flush(); - } - // Finally, add the bot to the connections active bots. - connection.addBot(this.config.id, bot); - } catch (Exception exception) { - noInternet = true; -// MicroMemory.reset(); - return null; - } - return null; - } - - /** - * Load, compile, and add the state machine from the Self source code. - * - * @param bot bot - * @param text text - */ - public void loadSelf(Bot bot, String text) { - - Network network = bot.memory().newMemory(); - Vertex language = network.createVertex(bot.mind().getThought(Language.class).getPrimitive()); - SelfCompiler compiler = SelfCompiler.getCompiler(); - Vertex stateMachine = compiler.parseStateMachine(text, false, network); - SelfCompiler.getCompiler().pin(stateMachine); - language.addRelationship(Primitive.STATE, stateMachine); - network.save(); - } - - @Override - protected void onPostExecute(String result) { - super.onPostExecute(result); - } -} \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java index d8c26ab63134370d42b0282926bcb658e56861f6..2c4c45a4a6d9fbb428fc2988f2aff31a788773f2 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java @@ -50,155 +50,135 @@ import org.botlibre.sdk.Credentials; * and accessed bots locally. */ public class MicroConnection extends SDKConnection implements TextListener { - private WebMediumConfig config; - protected Map activeBots = new HashMap(); - public static AvatarConfig avatarConfig; - public TextOutput message; - public static Bot bot; - - /** - * Create a micro/offline SDK connection. - */ - public MicroConnection() { - } - - /** - * Create a micro/offline SDK connection. - * Use the credentials to enable online support. - * - * @param credentials credentials - */ - public MicroConnection(Credentials credentials) { - this.credentials = credentials; - this.url = credentials.url; - } - - public void addBot(String id, Bot bot) { - activeBots.put(id, bot); - } - - public Bot getBot(String id) { - return activeBots.get(id); - } - - public static Bot getBot() { - return bot; - } - - /** - * Fetch the local object. - * - * @param config config - * @param - * @return Fetch the local object - */ - public T fetch(T config) { - this.config = config; - MicroMemory.storageFileName = config.name; - int id = Integer.parseInt(config.id); - bot = loadBot(config.name, id); - addBot(config.id, bot); - if(!(config instanceof InstanceConfig)){ - return super.fetch(config); - } - return config; - } - - /** - * Return the bot's voice configuration. - * - * @param config config - * @return Return the bot's voice configuration. - */ - public VoiceConfig getVoice(InstanceConfig config) { - VoiceConfig voice = new VoiceConfig(); - voice.nativeVoice = true; - voice.language = "en"; - return voice; - } - - /** - * sendMessage - * - * @param message sendMessage - */ - public synchronized void sendMessage(TextOutput message) { - this.message = message; - notifyAll(); - } - - /** - * loadBot - * - * @param name name - * @param id id - * @return loadBot - */ - public Bot loadBot(String name, int id) { - boolean exists = MicroMemory.checkExists(); - Bot.CONFIG_FILE = "config.xml"; - Bot bot = Bot.createInstance(Bot.CONFIG_FILE, name, true); - bot.setName(name); - - Language language = bot.mind().getThought(Language.class); - language.setLearnGrammar(false); - //if (id != 2) { - language.setLearningMode(LearningMode.Disabled); - Comprehension comprehension = bot.mind().getThought(Comprehension.class); - comprehension.setEnabled(false); - Consciousness consciousness = bot.mind().getThought(Consciousness.class); - consciousness.setEnabled(false); - Sense sense = bot.awareness().getSense(Wiktionary.class); - sense.setIsEnabled(false); - //} - - if (!exists) { - try { - new Bootstrap().bootstrapSystem(bot, false); - loadResScript(bot, "/assets/servicebot.res"); - loadResScript(bot, "/assets/farewells.res"); - loadResScript(bot, "/assets/pizza.res"); - loadSelfScript(bot, "/assets/pizza.self"); - bot.memory().shutdown(); - } catch (Exception exception) { - } - } - return bot; - } - - /** - * loadResScript - * - * @param bot bot - * @param fileName fileName - */ - public void loadResScript(Bot bot, String fileName) { - URL url = getClass().getResource(fileName); - bot.awareness().getSense(TextEntry.class).loadChatFile(url, "Response List", "", false, true); - } - - /** - * loadSelfScript - * - * @param bot bot - * @param fileName fileName - */ - public void loadSelfScript(Bot bot, String fileName) { - loadSelfScript(bot, getClass().getResource(fileName)); - } - - /** - * loadSelfScript - * - * @param bot bot - * @param url url - */ - public void loadSelfScript(Bot bot, URL url) { - Network network = bot.memory().getShortTermMemory(); - Vertex language = network.createVertex(new Primitive(Language.class.getName())); - SelfCompiler compiler = SelfCompiler.getCompiler(); - Vertex stateMachine = compiler.parseStateMachine(url, "", false, network); - language.addRelationship(Primitive.STATE, stateMachine); - SelfCompiler.getCompiler().pin(stateMachine); - } + protected Map activeBots = new HashMap(); + public static AvatarConfig avatarConfig; + public TextOutput message; + private static Bot bot; + + /** + * Create a micro/offline SDK connection. + */ + public MicroConnection() { + } + + /** + * Create a micro/offline SDK connection. + * Use the credentials to enable online support. + * + * @param credentials credentials + */ + public MicroConnection(Credentials credentials) { + this.credentials = credentials; + this.url = credentials.url; + } + + public void addBot(String id, Bot bot) { + activeBots.put(id, bot); + } + + public Bot getBot(String id) { + return activeBots.get(id); + } + + public static Bot getBot() { + return bot; + } + + /** + * Fetch the local object. + * + * @param config config + * @param + * @return Fetch the local object + */ + public T fetch(T config) { + addBot(config.id, bot); + if (!(config instanceof InstanceConfig)) { + return super.fetch(config); + } + return config; + } + + /** + * sendMessage + * + * @param message sendMessage + */ + public void sendMessage(TextOutput message) { + this.message = message; + } + + /** + * loadBot + * + * @param name name + * @param id id + * @return loadBot + */ + public Bot loadBot(String name, int id) { + boolean exists = MicroMemory.checkExists(); + Bot bot = new Bot(); + bot.setName(name); + + Language language = bot.mind().getThought(Language.class); + language.setLearnGrammar(false); + //if (id != 2) { + language.setLearningMode(LearningMode.Disabled); + Comprehension comprehension = bot.mind().getThought(Comprehension.class); + comprehension.setEnabled(false); + Consciousness consciousness = bot.mind().getThought(Consciousness.class); + consciousness.setEnabled(false); + Sense sense = bot.awareness().getSense(Wiktionary.class); + sense.setIsEnabled(false); + //} + + if (!exists) { + try { + new Bootstrap().bootstrapSystem(bot, false); + loadResScript(bot, "/assets/servicebot.res"); + loadResScript(bot, "/assets/farewells.res"); + loadResScript(bot, "/assets/pizza.res"); + loadSelfScript(bot, "/assets/pizza.self"); + bot.memory().shutdown(); + } catch (Exception exception) { + } + } + return bot; + } + + /** + * loadResScript + * + * @param bot bot + * @param fileName fileName + */ + public void loadResScript(Bot bot, String fileName) { + URL url = getClass().getResource(fileName); + bot.awareness().getSense(TextEntry.class).loadChatFile(url, "Response List", "", false, true); + } + + /** + * loadSelfScript + * + * @param bot bot + * @param fileName fileName + */ + public void loadSelfScript(Bot bot, String fileName) { + loadSelfScript(bot, getClass().getResource(fileName)); + } + + /** + * loadSelfScript + * + * @param bot bot + * @param url url + */ + public void loadSelfScript(Bot bot, URL url) { + Network network = bot.memory().getShortTermMemory(); + Vertex language = network.createVertex(new Primitive(Language.class.getName())); + SelfCompiler compiler = SelfCompiler.getCompiler(); + Vertex stateMachine = compiler.parseStateMachine(url, "", false, network); + language.addRelationship(Primitive.STATE, stateMachine); + SelfCompiler.getCompiler().pin(stateMachine); + } } \ No newline at end of file diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java index c364cd21a4ddf239d018cdfbcd6da41d51807e50..de5ffd0d7e58862a5ac3af6065df17a0eb7cc14c 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java @@ -46,14 +46,12 @@ public class ChatListProvicer extends BaseItemProvider { } Object message = getItem(i); Text messageView = (Text) cpt.findComponentById(ResourceTable.Id_messageView); - Image userView = (Image) cpt.findComponentById(ResourceTable.Id_userView); if (message instanceof ChatConfig) { ChatConfig config = (ChatConfig) message; messageView.setText(config.message); } else if (message instanceof ChatResponse) { ChatResponse config = (ChatResponse) message; messageView.setText(Utils.stripTags(config.message)); - String avatar = ((ChatAbility) this.slice).getAvatarIcon(config); } return cpt; diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java deleted file mode 100644 index 49fb24e5d366193acb5d67f0919bfa8d7e905647..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.botlibre.sdk.slice; - -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.util.LogUtils; -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.content.Intent; -import ohos.agp.window.dialog.CommonDialog; -import ohos.agp.window.dialog.IDialog; - -public class MainAbilitySlice extends AbilitySlice { - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_main); - } - - @Override - public void onActive() { - super.onActive(); - } - - @Override - public void onForeground(Intent intent) { - super.onForeground(intent); - } - - - public static void showMessage(String title, String message, AbilitySlice Ability) { - try { - CommonDialog dialog = new CommonDialog(Ability); - dialog.setContentText(message); - if (title != null) { - dialog.setTitleText(title); - } - dialog.setButton(CommonDialog.BUTTON1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - } - }); - dialog.show(); - } catch (Exception exception) { - LogUtils.e("showMessage", exception.toString()); - } - } - - public static void showMessage(String message, AbilitySlice Ability) { - showMessage(null, message, Ability); - } -} diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java index bce9ffe8c242a71cc0aa5b3ac96ba64fb6084abd..0d2563939d55dad1304e1a72365ab87737b6f8bf 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java @@ -36,7 +36,6 @@ import java.util.concurrent.atomic.AtomicInteger; * @param * @param * @param - * @author:hhh * @since 2021-05-08 */ public abstract class AsyncTask { @@ -82,7 +81,7 @@ public abstract class AsyncTask { protected void done() { super.done(); try { - postResult(get()); + postResult(super.get()); } catch (InterruptedException | ExecutionException e) { e.getMessage(); } @@ -118,7 +117,6 @@ public abstract class AsyncTask { /** * 可以回调的一些函数 */ - @MainThread protected void onPreExecute() { } @@ -135,14 +133,12 @@ public abstract class AsyncTask { * * @param result */ - @MainThread protected void onPostExecute(Result result) { } /** * onCancelled */ - @MainThread protected void onCancelled() { } @@ -151,14 +147,12 @@ public abstract class AsyncTask { * * @param progress */ - @MainThread protected void onProgressUpdate(Progress... progress) { } /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ private static class InnerUiHandler extends EventHandler { @@ -198,7 +192,6 @@ public abstract class AsyncTask { /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ public enum Status { @@ -262,7 +255,6 @@ public abstract class AsyncTask { * * @param * @param - * @author:hello * @since 2021-04-25 */ private abstract static class WorkRunnable implements Callable { @@ -276,7 +268,6 @@ public abstract class AsyncTask { * InnerUiHandler * * @param - * @author:hello * @since 2021-04-25 */ private static class AsyncTaskResult { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Constant.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Constant.java index 2038bcd9f3ab6f31ef3ed232145ee810afff36f1..63627c1e327c2fae500dff3b238b6e5d829fbc67 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Constant.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Constant.java @@ -18,7 +18,6 @@ package org.botlibre.sdk.util; /** * 常量工具类 * - * @author: ColorPicker * @since 2021-04-16 */ public final class Constant { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java index 9629cb0ba876eae2c207eba41ac2a4fb6a79441b..1ef2134a46013a0cd655657d0b6a06d492ce86fd 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java @@ -21,7 +21,6 @@ import ohos.hiviewdfx.HiLogLabel; /** * Log工具类 * - * @author:turnlayout * @since 2021-04-16 */ public final class LogUtils { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/MainThread.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/MainThread.java deleted file mode 100644 index 22487dec32617bd1033c3ac26a49d2f9ebedf86a..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/MainThread.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.CLASS; - -/** - * 注解 - * - * @author:turnlayout - * @since 2021-04-16 - */ -@Documented -@Retention(CLASS) -@Target({METHOD, CONSTRUCTOR, TYPE, PARAMETER}) -public @interface MainThread { -} diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java index d98fdc2b0dc053c102ce53400fabd58f5cb962d8..518720442318ce7324b8c6cd609785d91e9fcfb9 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java @@ -23,7 +23,6 @@ import ohos.data.preferences.Preferences; /** * PreferencesUtils * - * @author:username * @since 2021-05-10 */ public class PreferencesUtils { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java deleted file mode 100644 index 01cbef0229d910b8d378736f00c67bee32cf80cd..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import ohos.agp.components.AttrSet; -import ohos.agp.components.element.Element; -import ohos.agp.components.element.ElementScatter; -import ohos.agp.components.element.PixelMapElement; -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.global.resource.RawFileEntry; -import ohos.global.resource.Resource; -import ohos.global.resource.ResourceManager; -import ohos.global.resource.WrongTypeException; -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; - -import java.io.IOException; -import java.util.Optional; - -/** - * ResUtil工具类 - * - * @author:turnlayout - * @since 2021-04-16 - */ -public class ResUtil { - private ResUtil() { - } - - /** - * get the path from id - * - * @param context the context - * @param id - * @return the path from id - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - return path; - } - return path; - } - - /** - * get the color - * - * @param context the context - * @param id - * @return the color - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get string - * - * @param context the context - * @param id - * @return string of the given id - */ - public static String getString(Context context, int id) { - String result = ""; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getString(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * getPreferences - * - * @param context - * @param id - * @param format - * @return str - */ - public static String getString(Context context, int id, Object... format) { - return String.format(getString(context, id), format); - } - - /** - * get the pixel map - * - * @param context the context - * @param id - * @return the pixel map - */ - public static Optional getPixelMap(Context context, int id) { - String path = getPathById(context, id); - if (path == null || path.length() <= 0) { - return Optional.empty(); - } - RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); - ImageSource.SourceOptions options = new ImageSource.SourceOptions(); - options.formatHint = "image/png"; - ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); - try { - Resource asset = assetManager.openRawFile(); - ImageSource source = ImageSource.create(asset, options); - return Optional.ofNullable(source.createPixelmap(decodingOptions)); - } catch (IOException e) { - return Optional.empty(); - } - } - - /** - * get the Pixel Map Element - * - * @param context the context - * @param resId - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * getElement - * - * @param context - * @param resId - * @return Element - */ - public static Element getElement(Context context, int resId) { - return ElementScatter.getInstance(context).parse(resId); - } - - /** - * getColorValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getColorValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getColorValue().getValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getDimensionValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getDimensionValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getIntValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getIntegerValue(); - if (value != 0) { - return value; - } - return defaultValue; - } -} - diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java index 07761b975827f0205af3568e5d2341f2d0e8348a..bb0d9f8e58fbc7d68e2ef1a36e1f5b7b4512e9c0 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java @@ -15,43 +15,33 @@ package org.botlibre.sdk.util; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.element.Element; +import ohos.aafwk.ability.Ability; +import ohos.agp.components.Button; +import ohos.agp.components.Checkbox; +import ohos.agp.components.ComponentState; import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.components.element.VectorElement; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; -import ohos.agp.utils.Rect; +import ohos.agp.components.element.StateElement; import ohos.app.Context; import ohos.global.resource.NotExistException; import ohos.global.resource.RawFileEntry; import ohos.global.resource.Resource; import ohos.global.resource.ResourceManager; import ohos.global.resource.WrongTypeException; -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; -import ohos.media.image.common.PixelFormat; -import ohos.media.image.common.Size; +import org.botlibre.sdk.ResourceTable; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; /** * 资源工具类 * - * @author:hello * @since 2021-04-25 */ -public class ResUtils { +public final class ResUtils { private static final String TAG = "ResUtil"; - private static final int CONSTANT = 160; + private static final float CONSTANT = 160; private ResUtils() { } @@ -63,19 +53,8 @@ public class ResUtils { * @param vp vp * @return px */ - public static int vpToPx(Context context, float vp) { - return (int) (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp); - } - - /** - * px转vp - * - * @param context 上下文 - * @param px px - * @return vp - */ - public static int pxTovp(Context context, float px) { - return (int) (px / (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT)); + public static float vpToPx(Context context, float vp) { + return context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp; } /** @@ -84,139 +63,10 @@ public class ResUtils { * @param context 上下文 * @return 屏幕的宽,单位px */ - public static int getScreenWidth(Context context) { + public static float getScreenWidth(Context context) { return vpToPx(context, context.getResourceManager().getDeviceCapability().width); } - /** - * 获取屏幕的高 - * - * @param context 上下文 - * @return 屏幕的高,单位px - */ - public static int getScreenHeight(Context context) { - return vpToPx(context, context.getResourceManager().getDeviceCapability().height); - } - - /** - * 通过资源id获取路径 - * - * @param context 上下文 - * @param id 资源id - * @return 资源路径 - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - LogUtils.e("getPathById -> get null context"); - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getPathById -> get null ResourceManager"); - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - LogUtils.e("getPathById: " + e.getMessage()); - } - return path; - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static Color getNewColor(Context context, int id) { - return new Color(getColor(context, id)); - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - LogUtils.e("getColor -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getColor -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getColor: " + e.getMessage()); - } - return result; - } - - /** - * 通过资源id获取尺寸 - * - * @param context 上下文 - * @param id 资源Id - * @return 尺寸 - */ - public static float getDimen(Context context, int id) { - float result = 0; - if (context == null) { - LogUtils.e("getDimen -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getDimen: " + e.getMessage()); - } - return result; - } - - /** - * getBoolean - * - * @param context the context - * @param id the id - * @return get the boolean dimen value - */ - public static boolean getBoolean(Context context, int id) { - boolean result = false; - if (context == null) { - LogUtils.e("getBoolean -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException e) { - LogUtils.e("getBoolean -> IOException"); - } catch (NotExistException e) { - LogUtils.e("getBoolean -> NotExistException"); - } catch (WrongTypeException e) { - LogUtils.e("getBoolean -> WrongTypeException"); - } - return result; - } - /** * get string * @@ -226,143 +76,74 @@ public class ResUtils { */ public static String getString(Context context, int id) { String result = ""; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null context"); - return result; - } ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null ResourceManager"); - return result; - } try { result = manager.getElement(id).getString(); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> IOException"); + LogUtils.e("getString ->IOException"); } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> NotExistException"); + LogUtils.e("getString -> NotExistException"); } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> WrongTypeException"); + LogUtils.e("getString -> WrongTypeException"); } return result; } /** - * get the string array + * 设置button背景 * - * @param context the context - * @param id the string array id - * @return the string array + * @param button + * @param resId */ - public static String[] getStringArray(Context context, int id) { - String[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null ResourceManager"); - return result; - } + public static void setBackground(Button button, int resId) { + Resource bgResource = null; + button.setBackground(null); try { - result = manager.getElement(id).getStringArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> WrongTypeException"); + bgResource = button.getResourceManager().getResource(resId); + PixelMapElement pixBg = new PixelMapElement(bgResource); + button.setAroundElements(pixBg, null, null, null); + } catch (IOException | NotExistException e) { + e.getMessage(); } - return result; } /** - * get the int + * 设置button背景 * - * @param context the context - * @param id the int array - * @return the int array + * @param ability + * @param checkbox */ - public static int getInt(Context context, int id) { - int result = 0; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getInteger(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> WrongTypeException"); - } - return result; + public static void setCheckboxBg(Ability ability, Checkbox checkbox) { + StateElement stateElement = new StateElement(); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_checked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_unchecked)); + checkbox.setButtonElement(stateElement); } /** - * get the int array - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int[] getIntArray(Context context, int id) { - int[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> WrongTypeException"); - } - return result; - } - - /** - * get the vector drawable + * get the Pixel Map Element * * @param context the context - * @param id the drawable id - * @return the vector drawable + * @param resId + * @return the Pixel Map Element */ - public static VectorElement getVectorDrawable(Context context, int id) { - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getVectorDrawable -> get null context"); - return null; - } - return new VectorElement(context, id); + public static PixelMapElement getPixelMapDrawable(Context context, int resId) { + Optional optional = getPixelMap(context, resId); + return optional.map(PixelMapElement::new).orElse(null); } /** * get the pixel map * * @param context the context - * @param id the id + * @param id * @return the pixel map */ public static Optional getPixelMap(Context context, int id) { String path = getPathById(context, id); - if (path.isEmpty()) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> get empty path"); + if (path == null || path.length() <= 0) { return Optional.empty(); } RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); @@ -374,223 +155,31 @@ public class ResUtils { ImageSource source = ImageSource.create(asset, options); return Optional.ofNullable(source.createPixelmap(decodingOptions)); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> IOException"); + return Optional.empty(); } - return Optional.empty(); } /** - * get the Pixel Map Element + * get the path from id * * @param context the context - * @param resId the res id - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement - */ - public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle, - float sweepAngle) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } - - /** - * get the Element - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param rect the rect - * @return the Element + * @param id + * @return the path from id */ - public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.OVAL); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - element.setBounds(rect); - return element; - } - - /** - * get the Element - * - * @param inside the inside color - * @param rect the rect - * @return the Element - */ - public static Element getCustomRectGradientDrawable(Color inside, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.RECTANGLE); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setBounds(rect); - return element; - } - - /** - * 根据Resource获取背景(图片) - * - * @param resource 资源 - * @return 位图背景 - * @throws IOException - * @throws NotExistException - */ - public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException { - return new PixelMapElement(preparePixelmap(resource)); - } - - /** - * 根据Resource获取位图 - * - * @param resource 资源 - * @return 位图 - * @throws IOException - * @throws NotExistException - * @throws FileNotFoundException - */ - public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException { - ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions(); - ImageSource imageSource = null; - try { - imageSource = ImageSource.create(readResource(resource), srcOpts); - } finally { - close(resource); - } - if (imageSource == null) { - throw new FileNotFoundException(); - } - ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions(); - decodingOpts.desiredSize = new Size(0, 0); - decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0); - decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888; - - PixelMap pixelmap = imageSource.createPixelmap(decodingOpts); - return pixelmap; - } - - private static void close(Resource resource) { - if (resource != null) { - try { - resource.close(); - } catch (IOException e) { - Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage()); - } - } - } - - private static byte[] readResource(Resource resource) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bArr = new byte[1024]; - while (true) { - try { - int read = resource.read(bArr, 0, 1024); - if (read == -1) { - break; - } - byteArrayOutputStream.write(bArr, 0, read); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } finally { - try { - byteArrayOutputStream.close(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } - } - } - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource finish"); - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource len: " + byteArrayOutputStream.size()); - return byteArrayOutputStream.toByteArray(); - } - - /** - * rgb颜色值转换为rgba的ShapeElement - * - * @param rgbColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement6(int rgbColor) { - if (rgbColor < 0 && rgbColor >= -0xffffff) { - rgbColor = rgbColor + 0xffffff + 1; + public static String getPathById(Context context, int id) { + String path = ""; + if (context == null) { + return path; } - if (rgbColor > 0 && rgbColor <= 0xffffff) { - rgbColor = alphaColor(rgbColor, 1.0f); + ResourceManager manager = context.getResourceManager(); + if (manager == null) { + return path; } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbColor)); - return shapeElement; - } - - /** - * rgb颜色值转换为rgba - * - * @param rgbColor 颜色值 - * @param alpha 透明度 - * @return int - */ - public static int alphaColor(int rgbColor, float alpha) { - if (rgbColor < 0) { - rgbColor = rgbColor + 0xffffff + 1; + try { + path = manager.getMediaPath(id); + } catch (IOException | NotExistException | WrongTypeException e) { + return path; } - int rgb = Math.max(0, rgbColor) << 8; - int al = (int) (alpha * 255); - return rgb + al; - } - - /** - * 颜色值rgba转换为ShapeElement - * - * @param rgbaColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement8(int rgbaColor) { - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbaColor)); - return shapeElement; + return path; } } diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java deleted file mode 100644 index 898266f217f2e0c75fb7528212784016618b8e60..0000000000000000000000000000000000000000 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import org.botlibre.sdk.ResourceTable; -import ohos.aafwk.ability.Ability; -import ohos.agp.components.Button; -import ohos.agp.components.Checkbox; -import ohos.agp.components.ComponentState; -import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.StateElement; -import ohos.global.resource.NotExistException; -import ohos.global.resource.Resource; - -import java.io.IOException; - -/** - * ShapeUtils - * - * @author:username - * @since 2021-05-13 - */ -public class ShapeUtils { - private ShapeUtils() { - } - - /** - * 设置button背景 - * - * @param button - * @param resId - */ - public static void setBackground(Button button, int resId) { - Resource bgResource = null; - button.setBackground(null); - try { - bgResource = button.getResourceManager().getResource(resId); - PixelMapElement pixBg = new PixelMapElement(bgResource); - button.setAroundElements(pixBg, null, null, null); - } catch (IOException | NotExistException e) { - e.getMessage(); - } - } - - /** - * 设置button背景 - * - * @param ability - * @param checkbox - */ - public static void setCheckboxBg(Ability ability, Checkbox checkbox) { - StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_unchecked)); - checkbox.setButtonElement(stateElement); - } -} diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/TextStream.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/TextStream.java index 1366f761cbfb6c5971f935cf8bad0c42da1831c9..7cce43a70f306e2d170b135e604b9ae375aa447f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/TextStream.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/TextStream.java @@ -33,7 +33,7 @@ public class TextStream { public static final String HTTP =" \t\n\r\f\""; public static final String TOKENS =" \t\n\r\f.,:;!()?[]{}+=^&*\"`~|/\\<>"; public static final String TERMINATORS =".?!。"; - public static Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); + public static final Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); public static Set IGNORABLE = new HashSet(Arrays.asList(new String[]{"'","`", "\"", ","})); /** diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java index 8a7995bd5c02b4c8de8136000b4cafe7970d9b2b..d95dd3595242a802e7397a6dec6ee6883d50b30f 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java @@ -27,7 +27,6 @@ import ohos.app.Context; /** * ToastUtils * - * @author:258767-shengyu * @since 2021-04-20 */ public class ToastUtils { diff --git a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Utils.java b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Utils.java index 70462fcc327c7c2c6db32a63dd2248dd0cf83e78..c0d79872c48cd4ac42670e2fc01b7b939f03e691 100644 --- a/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Utils.java +++ b/BotLibre/entry/src/main/java/org/botlibre/sdk/util/Utils.java @@ -32,11 +32,9 @@ import java.util.regex.Pattern; * Utility class. */ public class Utils { - public static Random random = new Random(); - - public static Pattern httpRegex = Pattern.compile("\\b(?:https?|ftp|file):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]", Pattern.CASE_INSENSITIVE); - public static Pattern wwwRegex = Pattern.compile("((www\\.)[^\\s]+)", Pattern.CASE_INSENSITIVE); - public static Pattern emailRegex = Pattern.compile("(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+", Pattern.CASE_INSENSITIVE); + public static final Pattern httpRegex = Pattern.compile("\\b(?:https?|ftp|file):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]", Pattern.CASE_INSENSITIVE); + public static final Pattern wwwRegex = Pattern.compile("((www\\.)[^\\s]+)", Pattern.CASE_INSENSITIVE); + public static final Pattern emailRegex = Pattern.compile("(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+", Pattern.CASE_INSENSITIVE); /** * Includes http, www, images, video, audio, email address. diff --git a/BotLibre/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java b/BotLibre/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java index 905e2e38c5c233d359f4c2af025d853f4fd6ac0e..f17d303f76316abeaf958cbdfbb672eb8074393d 100644 --- a/BotLibre/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java +++ b/BotLibre/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java @@ -27,7 +27,6 @@ import org.junit.Test; /** * 单元测试类 * - * @author BotLibre * @since 2021-05-25 */ public class MainAbilityTest { @@ -37,8 +36,6 @@ public class MainAbilityTest { @Test public void onStart() { LogUtils.d("HiLog","单元测试"); - int pxTovp = ResUtils.pxTovp(ability.getApplicationContext(),1); - Assert.assertEquals(0, pxTovp); int height = ResUtils.getScreenHeight(ability.getApplicationContext()); HiLog.info(LABEL_LOG,height + ""); int width = ResUtils.getScreenWidth(ability.getApplicationContext()); diff --git a/BotLibreOffline/CHANGELOG.md b/BotLibreOffline/CHANGELOG.md index bd8486c3dc641e4c777c96dc0b45df63caf70331..903a98780efa5546d317ac65a47ac3bf0a7865fb 100644 --- a/BotLibreOffline/CHANGELOG.md +++ b/BotLibreOffline/CHANGELOG.md @@ -3,5 +3,4 @@ ohos 第二个版本,更新sdk6 ## 0.0.1-SNAPSHOT ohos 第一个版本 * 实现了原库的大部分api - * 鸿蒙的IntentConstants中没有跳转邮箱的action,故无法实现跳转邮箱功能 * 鸿蒙监听不到软键盘软键盘状态的改变,因此软键盘关闭后无法恢复页面布局 \ No newline at end of file diff --git a/BotLibreOffline/build.gradle b/BotLibreOffline/build.gradle index 8b4ed735fd4fd15aa69f97798dfe38beae5216e4..f0fed48a4512412c40b615d22d70fe57bd5dec43 100644 --- a/BotLibreOffline/build.gradle +++ b/BotLibreOffline/build.gradle @@ -2,17 +2,6 @@ apply plugin: 'com.huawei.ohos.app' ohos { - signingConfigs { - debug { - storeFile file('D:\\cer\\hmp12.p12') - storePassword '00000019ED3D37DFFB38AD51F65AAD2107E303EC2ACC9FD0722503FDA37C5A73FEF56F0B93B4770F1A' - keyAlias = 'qazwsx' - keyPassword '00000019E3A03A4F10F2A83920265A2263EB7CE1974E890700EFB7A83AED85E53158BA5EAF9F5C4AF9' - signAlg = 'SHA256withECDSA' - profile file('D:\\cer\\botlibreDebug.p7b') - certpath file('D:\\cer\\hmcer.cer') - } - } compileSdkVersion 6 defaultConfig { compatibleSdkVersion 5 diff --git a/BotLibreOffline/entry/src/main/config.json b/BotLibreOffline/entry/src/main/config.json index 9eeb695e15c72900f6333f07d7b68a97379aaa7b..8a125264467fcd0e8491534b118ca8c4bbf7a432 100644 --- a/BotLibreOffline/entry/src/main/config.json +++ b/BotLibreOffline/entry/src/main/config.json @@ -134,24 +134,54 @@ "name": "ohos.permission.ACCESS_BIOMETRIC_INTERNAL" }, { + "name": "ohos.permission.READ_USER_STORAGE", "reason": "Read User Storage", - "name": "ohos.permission.READ_USER_STORAGE" + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Camera", - "name": "ohos.permission.READ_MEDIA" + "name": "ohos.permission.READ_MEDIA", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Media", - "name": "ohos.permission.MEDIA_LOCATION" + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "get MICROPHONE", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.WRITE_USER_STORAGE", - "reason": "get WRITE_USER_STORAGE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.MICROPHONE", - "reason": "get MICROPHONE" + "reason": "get MICROPHONE", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "com.android.alarm.permission.SET_ALARM", diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java index fa87008d9337394bdc61592cc11c48d5806d9798..1b2e369246c78a388e4bb12014769417654545b7 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java @@ -23,11 +23,9 @@ package org.botlibre.sdk; * http://www.botlibre.com */ public class BOTlibreCredentials extends Credentials { - public static String DOMAIN = "www.botlibre.com"; - //public static String DOMAIN = "192.168.0.21:9080"; - public static String APP = ""; - //public static String APP = "/botlibre"; - public static String PATH = "/rest/api"; + public static final String DOMAIN = "www.botlibre.com"; + public static final String APP = ""; + public static final String PATH = "/rest/api"; public BOTlibreCredentials(String applicationId) { this.host = DOMAIN; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/LIVECHATlibreCredentials.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/LIVECHATlibreCredentials.java deleted file mode 100644 index fac6db6863d38b9b6abd0b4ce70592450d68b558..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/LIVECHATlibreCredentials.java +++ /dev/null @@ -1,38 +0,0 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -package org.botlibre.sdk; - -/** - * Credentials for use with hosted services on the LIVE CHAT libre website, a free live chat, chatrooms, forum, and chat bots that learn. - * http://www.livechatlibre.com - */ -public class LIVECHATlibreCredentials extends Credentials { - public static String DOMAIN = "www.livechatlibre.com"; - //public static String DOMAIN = "192.168.0.12:9080"; - public static String APP = ""; - //public static String APP = "/livechatlibre"; - public static String PATH = "/rest/api"; - - public LIVECHATlibreCredentials(String applicationId) { - this.host = DOMAIN; - this.app = APP; - this.url = "http://" + DOMAIN + APP + PATH; - this.applicationId = applicationId; - } -} \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java index 7fd6fd3996e2ee58208cbd1bebfd857b33aa969b..c0253994a34192c3c6f646e8f94364ad5a79152d 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java @@ -8,7 +8,6 @@ import ohos.agp.components.Component; import ohos.agp.components.DirectionalLayout; import ohos.agp.components.LayoutScatter; import ohos.agp.components.Text; -import ohos.agp.components.TextField; import ohos.agp.utils.Color; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.CommonDialog; @@ -24,7 +23,6 @@ import ohos.eventhandler.EventRunner; import ohos.media.audio.AudioManager; import ohos.media.audio.AudioRemoteException; import ohos.multimodalinput.event.TouchEvent; -import ohos.security.SystemPermission; import ohos.utils.net.Uri; import org.botlibre.knowledge.micro.MicroMemory; import org.botlibre.sdk.ability.BotSearchAbility; @@ -35,14 +33,12 @@ import org.botlibre.sdk.ability.HelpAbility; import org.botlibre.sdk.ability.LibreAbility; import org.botlibre.sdk.ability.ListTemplateView; import org.botlibre.sdk.ability.LoginAbility; -import org.botlibre.sdk.ability.actions.HttpGetTemplatesAction; import org.botlibre.sdk.ability.dialog.SpinnerDialogBuilder; import org.botlibre.sdk.ability.listener.LanguageListener; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.ability.war.StartWarAbility; import org.botlibre.sdk.config.AvatarConfig; import org.botlibre.sdk.config.AvatarMedia; -import org.botlibre.sdk.config.BotModeConfig; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChannelConfig; import org.botlibre.sdk.config.DomainConfig; @@ -65,8 +61,6 @@ import org.botlibre.sdk.util.PreferencesUtils; import java.awt.*; import java.io.File; import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; import java.util.List; import java.util.Optional; @@ -74,29 +68,39 @@ import static ohos.agp.components.Component.HIDE; import static ohos.agp.components.Component.VISIBLE; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; +/** + * MainAbility + * + * @since 2021-04-16 + */ public class MainAbility extends LibreAbility implements SelectListener, LanguageListener, Component.TouchEventListener { + + /** + * DEBUG + */ public static final boolean DEBUG = false; - public static final boolean ADULT = false; /** * Enter your application ID here. * You can get an application ID from any of the services websites (Bot Libre, Bot Libre for Business) */ - public static String applicationId = "enter your application id here"; + public static final String applicationId = "enter your application id here"; /** * Configure your connection credentials here. * Choose which service provider you wish to connect to. */ - public static SDKConnection connection, localConnection, remoteConnection; + private static SDKConnection localConnection, remoteConnection; + + private static SDKConnection connection; /** * To launch into a specific domain, enter the domain id here. */ - public static String domainId = null; - public static DomainConfig domain; - public static String defaultType = "Bots"; - public static boolean showAds = true; + private static String domainId = null; + private static DomainConfig domain; + private static String defaultType = "Bots"; + private static boolean showAds = true; /** * Choose your service provider using the correct credentials. @@ -105,34 +109,22 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag localConnection = new MicroConnection(new BOTlibreCredentials(applicationId)); remoteConnection = new SDKConnection(new BOTlibreCredentials(applicationId)); connection = localConnection; - if (domainId != null) { - domain = new DomainConfig(); - domain.id = domainId; - connection.setDomain(domain); - } if (DEBUG) { showAds = false; connection.setDebug(true); } } - public static String WEBSITE = "https://www.botlibre.com"; - public static final String WEBSITEHTTPS = "https://www.botlibre.com"; - public static String SERVER = "botlibre.com"; - /** * If you are building a single instance app, then you can set the instance id or name here, * and use this to launch it. */ - public static String launchInstanceId = ""; // i.e. "171" - public static String launchInstanceName = "Bot Libre!"; // i.e. "Help Bot" - public static String website = "https://www.botlibre.com"; - public static String prefix = "Bot"; - public static String launchSelfScriptID = ""; - public static String launchGreetingScriptID = ""; + private static String launchInstanceId = ""; // i.e. "171" + private static String launchInstanceName = "Bot Libre!"; // i.e. "Help Bot" + private static String website = "https://www.botlibre.com"; private Preferences cookies; private Text deleteBot; - + public static final String WEBSITEHTTPS = "https://www.botlibre.com"; public static SDKConnection getConnection() { return localConnection; @@ -142,7 +134,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * If you are building a single instance app, then you can set the launchType to * have this activity launch the bot, forum, or channel. */ - public static LaunchType launchType = LaunchType.Bot; + private static LaunchType launchType = LaunchType.Bot; @Override public void selectItem(String select) { @@ -157,99 +149,88 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag public void selectLanguageItem(String select) { } + public static void setDomain(DomainConfig domains) { + domain = domains; + } + + public static SDKConnection getRemoteConnection() { + return remoteConnection; + } + @Override public boolean onTouchEvent(Component component, TouchEvent touchEvent) { switch (touchEvent.getAction()) { case TouchEvent.PRIMARY_POINT_DOWN: - // Check whether the user pressed on the pointer. -// execcontentinfo.setScrollable(true); -// notifyAll(); break; default: } return true; } - public enum LaunchType {Browse, Bot, Forum, Channel} + /** + * LaunchType + * + * @since 2021-04-16 + */ + private enum LaunchType {Browse, Bot, Forum, Channel} - public static boolean online = true; + private static boolean online = true; - public static boolean handsFreeSpeech = true; - public static boolean listenInBackground = false; - public static boolean micConfig = true; + private static boolean handsFreeSpeech = true; + private static boolean listenInBackground = false; + private static boolean micConfig = true; // selected image from the listView of the offline Templates bots - public static int offlineSelectedImage; - - public static boolean hasRequestAvatar; - public static boolean sound = true; - public static boolean disableVideo; - public static boolean webm = true; - public static boolean hd; - public static boolean deviceVoice; - public static boolean customVoice; - public static boolean translate; - - public static boolean offlineSpeech = false; - - public static GraphicConfig gInstance; - public static WebMediumConfig instance; - public static ForumPostConfig post; - public static IssueConfig issue; - public static UserConfig user; - public static UserConfig viewUser; - public static String type = "Bots"; - public static BotModeConfig botMode = new BotModeConfig(); - public static VoiceConfig voice = new VoiceConfig(); - public static LearningConfig learning = new LearningConfig(); - public static AvatarMedia avatarMedia; - public static ResponseConfig response; - public static ScriptSourceConfig script; - public static String conversation; - public static String template = ""; - public static String currentPhotoPath; - public static List templates; - public static Object[] tags; - public static Object[] categories; - public static Object[] forumTags; - public static Object[] forumPostTags; - public static Object[] forumCategories; - public static Object[] channelTags; - public static Object[] channelCategories; - public static Object[] avatarTags; - public static Object[] scriptTags; - public static Object[] scriptCategories; - public static Object[] avatarCategories; - public static int volume; - - public static String contentRating; - public static Object[] domainTags; - public static Object[] domainCategories; - - public static String nameOfAvatar; - - public static Object[] graphicTags; - public static Object[] graphicCategories; - public static boolean showImages = true; - public static BrowseConfig browse = null; - public static BrowseConfig browsePosts = null; - public static BrowseConfig browseIssues = null; - public static List instances = new ArrayList(); - public static List posts = new ArrayList(); - public static List issues = new ArrayList(); - public static List avatarMedias = new ArrayList(); - public static MainAbility current; - public static boolean browsing; - public static boolean searching; - public static boolean searchingPosts; - public static boolean searchingIssues; - public static boolean wasDelete; - public static boolean importingBotScript = false; - public static boolean importingBotLog = false; - public static String[] languages = new String[]{ + private static int offlineSelectedImage; + private static boolean sound = true; + private static boolean disableVideo; + private static boolean webm = true; + private static boolean hd; + private static boolean deviceVoice; + private static boolean translate; + + private static boolean offlineSpeech = false; + private static WebMediumConfig instance; + private static ForumPostConfig post; + private static IssueConfig issue; + private static UserConfig user; + private static UserConfig viewUser; + private static String type = "Bots"; + private static VoiceConfig voice = new VoiceConfig(); + private static LearningConfig learning = new LearningConfig(); + private static ResponseConfig response; + private static ScriptSourceConfig script; + private static String conversation; + private static List templates; + private static Object[] tags; + private static Object[] categories; + private static Object[] forumTags; + private static Object[] forumCategories; + private static Object[] channelTags; + private static Object[] channelCategories; + private static Object[] scriptTags; + private static int volume; + + private static String contentRating; + private static Object[] domainTags; + private static Object[] domainCategories; + + private static String nameOfAvatar; + + private static Object[] graphicTags; + private static Object[] graphicCategories; + private static boolean showImages = true; + private static BrowseConfig browse = null; + private static BrowseConfig browsePosts = null; + private static List avatarMedias = new ArrayList(); + private static MainAbility current; + private static boolean browsing; + private static boolean searching; + private static boolean searchingPosts; + private static final String[] languages = new String[]{ "Default", "af - Afrikaans", "sq - Albanian", "ar - Arabic", "hy - Armenian", "az - Azerbaijani", - "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - Bulgarian", + "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - v Bulgarian", "ca - Catalan", "zh - Chinese", "hr - Croatian", "cs - Czech", "da - Danish", "nl - Dutch", "en - English", "et - Estonian", "fi - Finnish", "fr - French", "gl - Galician", "ka - Georgian", "de - German", "el - Greek", "gu - Gujarati", "ht - Haitian", "he - Hebrew", "hi - Hindi", "hu - Hungarian", "is - Icelandic", "id - Indonesian", "ga - Irish", "it - Italian", "ja - Japanese", "kn - Kannada", "kk - Kazakh", "ky - Kirghiz", "ko - Korean", @@ -259,97 +240,25 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag "tl - Tagalog", "tg - Tajik", "ta - Tamil", "tt - Tatar", "th - Thai", "tr - Turkish", "udm - Udmurt", "uk - Ukrainian", "ur - Urdu", "uz - Uzbek", "vi - Vietnamese", "cy - Welsh" }; - public static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; - public static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; - public static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - public static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; - public static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - public static String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; - public static String[] forkAccMode = new String[]{"Administrators", "Members", "Users", "Disabled"}; - public static String[] mediaAccessModes = new String[]{"Administrators", "Everyone", "Members", "Users", "Disabled"}; - public static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] scriptLanguages = new String[]{"Self", "AIML", "Response List", "Chat Log", "CVS"}; - public static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - public static String[] responseTypes = new String[]{"conversations", "responses", "greetings", "default", "flagged"}; - public static String[] durations = new String[]{"all", "day", "week", "month"}; - public static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; - public static String[] responseRestrictions = new String[]{"", "exact", "keyword", "required", "topic", "label", "previous", + private static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; + private static final String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; + private static final String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; + private static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; + private static String[] responseRestrictions = new String[]{"", "exact", "keyword", "required", "topic", "label", "previous", "repeat", "missing-keyword", "missing-required", "missing-topic", "patterns", "templates", "flagged", "corrections", "emotions", "actions", "poses"}; - public static String[] voices = new String[]{ - "cmu-slt", - "cmu-slt-hsmm", - "cmu-bdl-hsmm", - "cmu-rms-hsmm", - "dfki-prudence", - "dfki-prudence-hsmm", - "dfki-spike", - "dfki-spike-hsmm", - "dfki-obadiah", - "dfki-obadiah-hsmm", - "dfki-poppy", - "dfki-poppy-hsmm", - "bits1-hsmm", - "bits3", - "bits3-hsmm", - "dfki-pavoque-neutral-hsmm", - "camille", - "camille-hsmm-hsmm", - "jessica_voice-hsmm", - "pierre-voice-hsmm", - "enst-dennys-hsmm", - "istc-lucia-hsmm", - "voxforge-ru-nsh", - "dfki-ot", - "dfki-ot-hsmm", - "cmu-nk", - "cmu-nk-hsmm" - }; - public static String[] voiceMods = new String[]{ - "default", "child", "whisper", "echo", "robot" - }; - public static String[] voiceNames = new String[]{ - "English : US : Female : SLT", - "English : US : Female : SLT (hsmm)", - "English : US : Male : BDL (hsmm)", - "English : US : Male : RMS (hsmm)", - "English : GB : Female : Prudence", - "English : GB : Female : Prudence (hsmm)", - "English : GB : Male : Spike", - "English : GB : Male : Spike (hsmm)", - "English : GB : Male : Obadiah", - "English : GB : Male : Obadiah (hsmm)", - "English : GB : Female : Poppy", - "English : GB : Female : Poppy (hsmm)", - "German : DE : Female : Bits1 (hsmm)", - "German : DE : Male : Bits3", - "German : DE : Male : Bits3 (hsmm)", - "German : DE : Male : Pavoque (hsmm)", - "French : FR : Female : Camille", - "French : FR : Female : Camille (hsmm)", - "French : FR : Female : Jessica (hsmm)", - "French : FR : Male : Pierre (hsmm)", - "French : FR : Male : Dennys (hsmm)", - "Italian : IT : Male : Lucia (hsmm)", - "Russian : RU : Male : NSH (hsmm)", - "Turkish : TR : Male : OT", - "Turkish : TR : Male : OT (hsmm)", - "Telugu : TE : Female : NK", - "Telugu : TE : Female : NK (hsmm)" - }; Menu menu; - public static int templateID; - public Button spin; - public Button createInstanceButton; - public Button browseButton; - public Button menuButton; - public Button loginButton; - public Button chatButton; - public Button logoutButton; - public Button viewUserButton; - public Button helpButton; + private static int templateID; + private Button spin; + private Button createInstanceButton; + private Button browseButton; + private Button menuButton; + private Button loginButton; + private Button chatButton; + private Button logoutButton; + private Button viewUserButton; + private Button helpButton; @Override protected void onActive() { @@ -393,10 +302,306 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } - public static boolean ohos(Uri uri) { + public static String getType() { + return type; + } + + public static void setType(String types) { + type = types; + } + + public static String getDefaultType() { + return defaultType; + } + + public static String getLaunchInstanceId() { + return launchInstanceId; + } + + public static String getLaunchInstanceName() { + return launchInstanceName; + } + + public static void setLaunchInstanceName(String launchInstanceNames) { + launchInstanceName = launchInstanceNames; + } + + public static void setLaunchInstanceId(String launchInstanceIds) { + launchInstanceId = launchInstanceIds; + } + + public static void setListenInBackground(boolean listenInBackgrounds) { + listenInBackground = listenInBackgrounds; + } + + private static boolean ohos(Uri uri) { return "com.ohos.externalstorage.documents".equals(uri.getDecodedAuthority()); } + /** + * getTags + * + * @return tags + */ + public static Object[] getTags() { + return tags.clone(); + } + + /** + * setTags + * + * @param tag Object[] + */ + public static void setTags(Object[] tag) { + if (tag != null) { + tags = tag.clone(); + } + } + + + public Preferences getCookies() { + return cookies; + } + + public void setCookies(Preferences cookies) { + this.cookies = cookies; + } + + + public void setDeleteBot(Text deleteBot) { + this.deleteBot = deleteBot; + } + + /** + * getCategories + * + * @return dd + */ + public static Object[] getCategories() { + return categories.clone(); + } + + /** + * setCategories + * + * @param categorie + */ + public static void setCategories(Object[] categorie) { + if (categorie != null) { + categories = categorie.clone(); + } + } + + /** + * setForumTags + * + * @param forumTag + */ + public static void setForumTags(Object[] forumTag) { + if (forumTag != null) { + forumTags = forumTag.clone(); + } + } + + /** + * setForumCategories + * + * @param forumCategorie + */ + public static void setForumCategories(Object[] forumCategorie) { + if (forumCategorie != null) { + forumCategories = forumCategorie.clone(); + } + } + + /** + * getChannelTags + * + * @return dd + */ + public static Object[] getChannelTags() { + return channelTags.clone(); + } + + /** + * setChannelTags + * + * @param channelTag + */ + public static void setChannelTags(Object[] channelTag) { + if (channelTag != null) { + channelTags = channelTag.clone(); + } + } + + /** + * setChannelCategories + * + * @param channelCategorie + */ + public static void setChannelCategories(Object[] channelCategorie) { + if (channelCategorie != null) { + channelCategories = channelCategorie.clone(); + } + } + + + public static int getVolume() { + return volume; + } + + public static void setVolume(int volumes) { + volume = volumes; + } + + public static String getContentRating() { + return contentRating; + } + + public static void setContentRating(String contentRatings) { + contentRating = contentRatings; + } + + /** + * setDomainTags + * + * @param domainTag + */ + public static void setDomainTags(Object[] domainTag) { + if (domainTag != null) { + domainTags = domainTag.clone(); + } + } + + /** + * getDomainCategories + * + * @return dd + */ + public static Object[] getDomainCategories() { + return domainCategories.clone(); + } + + /** + * setDomainCategories + * + * @param domainCategorie + */ + public static void setDomainCategories(Object[] domainCategorie) { + if (domainCategorie != null) { + domainCategories = domainCategorie.clone(); + } + } + + /** + * setSyncNameOfAvatar + * + * @param nameOfAvatars + */ + private synchronized static void setSyncNameOfAvatar(String nameOfAvatars) { + nameOfAvatar = nameOfAvatars; + } + + /** + * setNameOfAvatar + * + * @param nameOfAvatar + */ + public static void setNameOfAvatar(String nameOfAvatar) { + setSyncNameOfAvatar(nameOfAvatar); + } + + public static Object[] getGraphicTags() { + return graphicTags.clone(); + } + + /** + * setGraphicTags + * + * @param graphicTag + */ + public static void setGraphicTags(Object[] graphicTag) { + if (graphicTag != null) { + graphicTags = graphicTag.clone(); + } + } + + /** + * setSyncGraphicCategories + * + * @param graphicCategorie + */ + private synchronized static void setSyncGraphicCategories(Object[] graphicCategorie) { + graphicCategories = graphicCategorie; + } + + /** + * setGraphicCategories + * + * @param graphicCategories + */ + public static void setGraphicCategories(Object[] graphicCategories) { + setSyncGraphicCategories(graphicCategories); + } + + /** + * isShowImages + * + * @return ss + */ + public static boolean isShowImages() { + return showImages; + } + + /** + * setSyncShowImages + * + * @param showImage + */ + private synchronized static void setSyncShowImages(boolean showImage) { + showImages = showImage; + } + + /** + * setShowImages + * @param showImages + */ + public static void setShowImages(boolean showImages) { + setSyncShowImages(showImages); + } + + public static BrowseConfig getBrowse() { + return browse; + } + + public static void setBrowse(BrowseConfig browses) { + browse = browses; + } + + public static void setBrowsePosts(BrowseConfig browsePost) { + browsePosts = browsePost; + } + + public static void setAvatarMedias(List avatarMedia) { + avatarMedias = avatarMedia; + } + + public static MainAbility getCurrent() { + return current; + } + + public static void setCurrent(MainAbility currentt) { + current = currentt; + } + + public static UserConfig getUser() { + return user; + } + + public static void setUser(UserConfig users) { + user = users; + } + /** * isTablet * @@ -404,11 +609,41 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * @return ds */ public static boolean isTablet(Context context) { -// return (context.getResourceManager().getConfiguration().isLayoutRTL -// & Configuration.AUTO_MODE) >= Configuration.AUTO_MODE; return true; } + public static boolean isDeviceVoice() { + return deviceVoice; + } + + public static void setDeviceVoice(boolean deviceVoices) { + deviceVoice = deviceVoices; + } + + public static boolean isOnline() { + return online; + } + + public static boolean isSound() { + return sound; + } + + public static void setSound(boolean sounds) { + sound = sounds; + } + + public static boolean isSearching() { + return searching; + } + + public static void setSearching(boolean searchings) { + searching = searchings; + } + + public static void setSearchingPosts(boolean searchingPost) { + searchingPosts = searchingPost; + } + /** * getActivity * @@ -416,17 +651,29 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * @return ff */ public static Class getActivity(WebMediumConfig config) { - if (config instanceof ChannelConfig) { - } else if (config instanceof ForumConfig) { - } else if (config instanceof InstanceConfig) { - } else if (config instanceof DomainConfig) { - } else if (config instanceof AvatarConfig) { - } else if (config instanceof ScriptConfig) { - } else if (config instanceof GraphicConfig) { - } return null; } + public static boolean isListenInBackground() { + return listenInBackground; + } + + public static boolean isHandsFreeSpeech() { + return handsFreeSpeech; + } + + public static boolean isDisableVideo() { + return disableVideo; + } + + public static void setDisableVideo(boolean disableVideos) { + disableVideo = disableVideos; + } + + public static void setHandsFreeSpeech(boolean handsFreeSpeechs) { + handsFreeSpeech = handsFreeSpeechs; + } + /** * error * @@ -482,6 +729,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + public static boolean isBrowsing() { + return browsing; + } + + public static void setBrowsing(boolean browsings) { + browsing = browsings; + } + /** * showMessage * @@ -553,7 +808,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } - public static Text execcontentinfo; + private static Text execcontentinfo; /** * showMessageInfo @@ -608,28 +863,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag showMessage(null, message, activity); } - /** - * prompt - * - * @param message - * @param activity - * @param text - * @param listener - */ - public static void prompt(String message, Ability activity, TextField text, IDialog.ClickedListener listener) { - CommonDialog dialog = new CommonDialog(activity); - dialog.setContentText(message); - dialog.setContentCustomComponent(text); - dialog.setButton(0, "OK", listener); - dialog.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - - } - }); - dialog.show(); - } - /** * confirm * @@ -650,65 +883,33 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag dialog.show(); } - /** - * getAllTemplates - * - * @param activity - * @return ds - */ - public static List getAllTemplates(Ability activity) { - if (templates == null) { - try { - HttpGetTemplatesAction action = new HttpGetTemplatesAction(activity); - action.postExecute(action.execute().get()); - if (action.getException() != null) { - templates = new ArrayList(); - } - } catch (Exception ignore) { - } - } - return templates; - } - - private final List mPermissions = - new LinkedList<>( - Arrays.asList( - SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE)); - @Override public void onStart(Intent intent) { super.onStart(intent); - searching = false; - browsing = false; - searchingPosts = false; - importingBotLog = false; - importingBotScript = false; + setSearching(false); + setBrowsing(false); + setSearchingPosts(false); if (user != null) { Preferences cookies = PreferencesUtils.getPreferences(this); cookies.putString("user", MainAbility.user.user); cookies.putString("token", MainAbility.user.token); cookies.flushSync(); } - current = this; + setCurrent(this); cookies = PreferencesUtils.getPreferences(this); // saved handsFreeSpeech toggle - load cookies. - handsFreeSpeech = cookies.getBoolean("handsfreespeech", handsFreeSpeech); - listenInBackground = cookies.getBoolean("listenInBackground", listenInBackground); - offlineSpeech = cookies.getBoolean("offlineSpeech", offlineSpeech); -// ChatAbility.DEBUG = cookies.getBoolean("debug", ChatAbility.DEBUG); //=============================================== - launchInstanceId = cookies.getString("instanceID", launchInstanceId); - launchInstanceName = cookies.getString("instanceName", launchInstanceName); + + setHandsFreeSpeech(cookies.getBoolean("handsfreespeech", handsFreeSpeech)); + setListenInBackground(cookies.getBoolean("listenInBackground", listenInBackground)); + setOfflineSpeech(cookies.getBoolean("offlineSpeech", offlineSpeech)); + setLaunchInstanceId(cookies.getString("instanceID", launchInstanceId)); + setLaunchInstanceName(cookies.getString("instanceName", launchInstanceName)); // saving the a number of array as an ID, for the sake of loading the // exact saved bot. - templateID = cookies.getInt("tempId", templateID); - nameOfAvatar = cookies.getString("nameOfAvatar", nameOfAvatar); - System.out.println("Name of avatar: " + nameOfAvatar); - // load memory: by bot's name - + setTemplateID(cookies.getInt("tempId", templateID)); + setNameOfAvatar(cookies.getString("nameOfAvatar", nameOfAvatar)); loadMemoryByBot(); - - micConfig = cookies.getBoolean("miconfig", micConfig); - + setMicConfig(cookies.getBoolean("miconfig", micConfig)); if (user == null) { String user = cookies.getString("user", null); String token = cookies.getString("token", null); @@ -737,20 +938,18 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag String nativeVoice = cookies.getString("nativeVoice", null); if (voice != null) { - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); - MainAbility.voice.voice = voice; - MainAbility.voice.language = language; - MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setVoice(new VoiceConfig()); + getVoice().voice = voice; + getVoice().language = language; + getVoice().nativeVoice = Boolean.valueOf(nativeVoice); + setDeviceVoice(getVoice().nativeVoice); } if (translate != null) { - MainAbility.translate = true; - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); - MainAbility.voice.language = language; - MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setTranslate(true); + setVoice(new VoiceConfig()); + getVoice().language = language; + getVoice().nativeVoice = Boolean.valueOf(nativeVoice); + setDeviceVoice(getVoice().nativeVoice); } } @@ -766,8 +965,8 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } resetView(); - searching = false; - hd = isTablet(this); + setSearching(false); + setHd(isTablet(this)); } @Override @@ -778,6 +977,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + public static WebMediumConfig getInstance() { + return instance; + } + + public static void setInstance(WebMediumConfig instances) { + instance = instances; + } + /** * initChat */ @@ -921,16 +1128,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * resetView */ public void loadMemoryByBot() { - MicroMemory.storageDir = getFilesDir(); - List items = new ArrayList(); + List items = null; items = ListTemplateView.retriveTemplates(); OfflineTemplateConfig oneItem; - oneItem = items.get(templateID); + oneItem = items.get(getTemplateID()); System.out.println("StorageFileName :" + oneItem.getTitle()); - offlineSelectedImage = oneItem.getImageId(); - MicroMemory.storageFileName = oneItem.getTitle(); - launchInstanceName = oneItem.getTitle(); - launchInstanceId = oneItem.getId(); + setOfflineSelectedImage(oneItem.getImageId()); + setLaunchInstanceName(oneItem.getTitle()); + setLaunchInstanceId(oneItem.getId()); } /** @@ -945,41 +1150,42 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } }); - - if (domain != null) { - } - - resetMenu(this.menu); resetLast(); } + public static void setTranslate(boolean translates) { + translate = translates; + } + + public static boolean isTranslate() { + return translate; + } + /** * resetLast */ public void resetLast() { - if (type.equals("Chat Bot Wars")) { + if (getType().equals("Chat Bot Wars")) { war(); return; } - if (type == null) { - type = MainAbility.defaultType; - } + setType(defaultType); Button button = (Button) findComponentById(ResourceTable.Id_lastButton); if (button != null) { Preferences cookies = PreferencesUtils.getPreferences(this); String last = null; - if (type.equals("Forums")) { + if (getType().equals("Forums")) { last = cookies.getString("forum", null); - } else if (type.equals("Live Chat")) { + } else if (getType().equals("Live Chat")) { last = cookies.getString("channel", null); - } else if (type.equals("Domains")) { + } else if (getType().equals("Domains")) { last = cookies.getString("domain", null); - } else if (type.equals("Avatars")) { + } else if (getType().equals("Avatars")) { last = cookies.getString("avatar", null); - } else if (type.equals("Scripts")) { + } else if (getType().equals("Scripts")) { last = cookies.getString("script", null); - } else if (type.equals("Graphics")) { + } else if (getType().equals("Graphics")) { last = cookies.getString("graphic", null); } else { last = cookies.getString("instance", null); @@ -1083,19 +1289,16 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag public void logout() { connection.disconnect(); - user = null; - instance = null; - conversation = null; - post = null; - posts = new ArrayList(); - instances = new ArrayList(); - domain = null; - tags = null; - categories = null; - learning = null; - voice = null; - customVoice = false; - translate = false; + setUser(null); + setInstance(null); + setConversation(null); + setDomain(null); + setPost(null); + setTags(null); + setCategories(null); + setLearning(null); + setVoice(null); + setTranslate(false); Preferences editor = PreferencesUtils.getPreferences(this); editor.delete("user"); @@ -1188,6 +1391,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag online = result; } + public static void setConnection(SDKConnection connection) { + MainAbility.connection = connection; + } /** * help @@ -1200,7 +1406,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * viewUser */ public void viewUser() { - viewUser = user; + setViewUser(user); } /** @@ -1228,10 +1434,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag return; } if (type == null) { - type = MainAbility.defaultType; - } - if (type.equals("Bots")) { - MainAbility.template = ""; + setType(defaultType); } } @@ -1240,7 +1443,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag */ public void search() { if (type == null) { - type = MainAbility.defaultType; + setType(defaultType); } if (type.equals("Bots")) { startOpenAbility(this, BotSearchAbility.class.getName()); @@ -1293,7 +1496,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } else if (type.equals("Avatars")) { config.type = "Avatar"; } else if (type.equals("Scripts")) { - importingBotScript = false; config.type = "Script"; } else if (type.equals("Graphics")) { config.type = "Graphic"; @@ -1313,8 +1515,8 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } else if (launchType == LaunchType.Channel) { config = new ChannelConfig(); } - config.id = launchInstanceId; - config.name = launchInstanceName; + config.id = getLaunchInstanceId(); + config.name = getLaunchInstanceName(); } /** @@ -1326,29 +1528,24 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag // the launch type is bot. if (MainAbility.launchType == LaunchType.Bot) { if (null == instance || null == this.instance.name || this.instance.name.equals("")) { - ListTemplateView.offlineTemplate = true; + ListTemplateView.setOfflineTemplate(true); if (cookies.getString("botName", "").equals("")) { startOpenAbility(this, ListTemplateView.class.getName()); } else { config = new InstanceConfig(); - MainAbility.launchInstanceId = cookies.getString("botID", ""); - MainAbility.launchInstanceName = cookies.getString("botName", ""); - config.id = MainAbility.launchInstanceId; - config.name = MainAbility.launchInstanceName; + setLaunchInstanceId(cookies.getString("botID", "")); + setLaunchInstanceName(cookies.getString("botName", "")); + config.id = getLaunchInstanceId(); + config.name = getLaunchInstanceName(); MicroConnection microConnection = (MicroConnection) MainAbility.getConnection(); microConnection.fetch(config); - if (MainAbility.launchInstanceName.contains("Assistance")) { + if (getLaunchInstanceName().contains("Assistance")) { startOpenAbility(MainAbility.this, ChatAbility2.class.getName()); } else { startOpenAbility(MainAbility.this, ChatAbility.class.getName()); } } - } else { } - } else if (MainAbility.launchType == LaunchType.Forum) { - config = new ForumConfig(); - } else if (MainAbility.launchType == LaunchType.Channel) { - config = new ChannelConfig(); } } @@ -1367,7 +1564,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag cookies.flushSync(); } - public static String selectInfo = ""; + private static String selectInfo = ""; /** * changeLanguage @@ -1382,9 +1579,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag CommonDialog dialog = new CommonDialog(MainAbility.this); setOnline(true); -// dialog.setTitleText(" Languages"); dialog.setSize(displayAttributes.width - 100, displayAttributes.width - 500); -// dialog.setContentText("Select your language"); dialog.setContentCustomComponent(layout); dialog.show(); @@ -1415,6 +1610,101 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * @param fileName */ public static void readZipAvatars(Ability activity, String fileName) { - String args[] = fileName.split("\\s+"); + } + + public static void setLearning(LearningConfig learnings) { + learning = learnings; + } + + public static String getConversation() { + return conversation; + } + + public static void setConversation(String conversations) { + conversation = conversations; + } + + public static boolean isOfflineSpeech() { + return offlineSpeech; + } + + public static void setOfflineSpeech(boolean offlineSpeechs) { + offlineSpeech = offlineSpeechs; + } + + public static int getTemplateID() { + return templateID; + } + + public static void setTemplateID(int templateIDs) { + templateID = templateIDs; + } + + public static void setMicConfig(boolean micConfigs) { + micConfig = micConfigs; + } + + public static VoiceConfig getVoice() { + return voice; + } + + public static void setVoice(VoiceConfig voices) { + voice = voices; + } + + public static boolean isHd() { + return hd; + } + + public static void setHd(boolean hds) { + hd = hds; + } + + public static void setPost(ForumPostConfig posts) { + post = posts; + } + + public static void setViewUser(UserConfig viewUsers) { + viewUser = viewUsers; + } + + public static void setOfflineSelectedImage(int offlineSelectedImages) { + offlineSelectedImage = offlineSelectedImages; + } + + public static boolean isWebm() { + return webm; + } + + public static void setWebm(boolean webms) { + webm = webms; + } + + public static String[] getContentRatings() { + return contentRatings.clone(); + } + + public static String[] getLanguages() { + return languages.clone(); + } + + public static String[] getTypes() { + return types.clone(); + } + + /** + * getSelectInfo + * @return dd + */ + public static String getSelectInfo() { + return selectInfo; + } + + /** + * setSelectInfo + * @param selectInf + */ + public static void setSelectInfo(String selectInf) { + selectInfo = selectInf; } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MyApplication.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MyApplication.java index 66bf82c230ced8e1b8e94e9705a26205f58bb26b..6a288620a1052fb2d68985641b44d090be2a26e6 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MyApplication.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/MyApplication.java @@ -9,10 +9,14 @@ public class MyApplication extends AbilityPackage { @Override public void onInitialize() { super.onInitialize(); - mContext = getApplicationContext(); + setmContext(getApplicationContext()); } public static Context getAppContext(){ return mContext; } + + public static void setmContext(Context mContext) { + MyApplication.mContext = mContext; + } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java index bc5b79b864ca48007c774eac7d640b89d596a15c..9fcf8e3627ee5ed046539b5ff113e5ed59856743 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java @@ -98,15 +98,10 @@ import javax.xml.parsers.DocumentBuilderFactory; * @since 2021-04-16 */ public class SDKConnection { - protected static String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; - protected static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - protected static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - protected static String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; - protected static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - protected static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; - + private static final String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; + private static final String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; + private static final String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; + private static final String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; protected String url; protected UserConfig user; protected DomainConfig domain; @@ -141,10 +136,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-user", config.toXML()); Element root = parse(xml); - if (root == null) { - this.user = null; - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -168,9 +159,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/" + api, config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { result.parseXML(root); } catch (Exception exception) { @@ -210,9 +198,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/view-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -238,52 +223,6 @@ public class SDKConnection { } } - /** - * fetch - * - * @param config - * @return dd - */ - public ForumPostConfig fetch(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-forum-post", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ForumPostConfig post = new ForumPostConfig(); - post.parseXML(root); - return post; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * fetch - * - * @param config - * @return dd - */ - public IssueConfig fetch(IssueConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-issue", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - IssueConfig issue = new IssueConfig(); - issue.parseXML(root); - return issue; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * create * @@ -295,13 +234,12 @@ public class SDKConnection { config.addCredentials(this); String xml = POSTUpdate(ability, this.url + "/create-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); - user.parseXML(root); - this.user = user; + if(root != null){ + user.parseXML(root); + this.user = user; + } return user; } catch (Exception exception) { this.exception = SDKException.parseFailure(exception); @@ -319,9 +257,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-forum-post", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ForumPostConfig post = new ForumPostConfig(); post.parseXML(root); @@ -342,9 +277,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-issue", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { IssueConfig issue = new IssueConfig(); issue.parseXML(root); @@ -366,9 +298,7 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } + try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -390,33 +320,7 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = (T) config.getClass().newInstance(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** - * update - * - * @param config - * @param - * @return result - */ - public T update(T config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-" + config.getType(), config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -427,31 +331,6 @@ public class SDKConnection { } } - - /** - * saveResponse - * - * @param config - * @return result - */ - public ResponseConfig saveResponse(ResponseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/save-response", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ResponseConfig response = new ResponseConfig(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** * delete * @@ -669,32 +548,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/post-chat", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } - try { - ChatResponse response = new ChatResponse(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * avatarMessage - * - * @param config - * @return result - */ - public ChatResponse avatarMessage(AvatarMessage config) { - config.addCredentials(this); - String xml = POST(this.url + "/avatar-message", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } try { ChatResponse response = new ChatResponse(); response.parseXML(root); @@ -705,53 +558,6 @@ public class SDKConnection { } } - /** - * getAdmins - * - * @param config - * @return result - */ - public List getAdmins(WebMediumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-" + config.getType() + "-admins", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - UserConfig user = new UserConfig(); - user.parseXML((Element) root.getChildNodes().item(index)); - users.add(user.user); - } - return users; - } - - /** - * getUsers - * - * @param usersCSV - * @return result - */ - public List getUsers(String usersCSV) { - UserConfig config = new UserConfig(); - config.user = usersCSV; - config.addCredentials(this); - String xml = POST(this.url + "/get-users", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - Element child = (Element) root.getChildNodes().item(index); - UserConfig userConfig = new UserConfig(); - userConfig.parseXML(child); - users.add(userConfig); - } - return users; - } - /** * getPosts * @@ -763,9 +569,6 @@ public class SDKConnection { String xml = POST(this.url + "/get-forum-posts", config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { ForumPostConfig post = new ForumPostConfig(); post.parseXML((Element) root.getChildNodes().item(index)); @@ -785,9 +588,7 @@ public class SDKConnection { String xml = POST(this.url + "/get-issues", config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } + for (int index = 0; index < root.getChildNodes().getLength(); index++) { IssueConfig issue = new IssueConfig(); issue.parseXML((Element) root.getChildNodes().item(index)); @@ -796,49 +597,6 @@ public class SDKConnection { return instances; } - /** - * getCategories - * - * @param config - * @return result - */ - public List getCategories(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-categories", config.toXML()); - List categories = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return categories; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ContentConfig category = new ContentConfig(); - category.parseXML((Element) root.getChildNodes().item(index)); - categories.add(category); - } - return categories; - } - - /** - * getTags - * - * @param config - * @return result - */ - public List getTags(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-tags", config.toXML()); - List tags = new ArrayList(); - tags.add(""); - Element root = parse(xml); - if (root == null) { - return tags; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - tags.add(((Element) root.getChildNodes().item(index)).getAttribute("name")); - } - return tags; - } - /** * getTemplates * @@ -848,9 +606,7 @@ public class SDKConnection { String xml = GET(this.url + "/get-all-templates"); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } + for (int index = 0; index < root.getChildNodes().getLength(); index++) { InstanceConfig instance = new InstanceConfig(); instance.parseXML((Element) root.getChildNodes().item(index)); @@ -870,9 +626,6 @@ public class SDKConnection { String xml = POST(this.url + "/get-" + config.getType() + "-users", config.toXML()); List users = new ArrayList(); Element root = parse(xml); - if (root == null) { - return users; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { UserConfig user = new UserConfig(); user.parseXML((Element) root.getChildNodes().item(index)); @@ -967,55 +720,6 @@ public class SDKConnection { } } - /** - * updateIcon - * - * @param file - * @param config - * @param - * @return result - */ - public T updateIcon(String file, T config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-" + config.getType() + "-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = (T) config.getClass().newInstance(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * updateIcon - * - * @param file - * @param config - * @return result - */ - public UserConfig updateIcon(String file, UserConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-user-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new UserConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * POSTIMAGE * @@ -1184,29 +888,6 @@ public class SDKConnection { return null; } - /** - * getVoice - * - * @param config - * @return voice - */ - public VoiceConfig getVoice(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-voice", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - VoiceConfig voice = new VoiceConfig(); - voice.parseXML(root); - return voice; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * getDefaultResponses * @@ -1218,9 +899,6 @@ public class SDKConnection { String xml = POST(this.url + "/get-default-responses", config.toXML()); List defaultResponses = new ArrayList(); Element root = parse(xml); - if (root == null) { - return defaultResponses; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { defaultResponses.add(((Element) root.getChildNodes().item(index)).getChildNodes().item(0).getTextContent()); } @@ -1238,9 +916,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/get-learning", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { LearningConfig learning = new LearningConfig(); learning.parseXML(root); @@ -1269,9 +944,7 @@ public class SDKConnection { String xml = POSTUpdate(ability, this.url + type, config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } + for (int index = 0; index < root.getChildNodes().getLength(); index++) { WebMediumConfig instance = null; if (config.type.equals("Bot")) { @@ -1306,9 +979,7 @@ public class SDKConnection { String xml = POST(this.url + "/get-avatar-media", config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } + for (int index = 0; index < root.getChildNodes().getLength(); index++) { AvatarMedia instance = new AvatarMedia(); instance.parseXML((Element) root.getChildNodes().item(index)); @@ -1328,30 +999,6 @@ public class SDKConnection { POST(this.url + "/save-script-source", config.toXML()); } - - /** - * getBotScripts - * - * @param config - * @return botScripts - */ - public List getBotScripts(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-bot-scripts", config.toXML()); - List botScripts = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return botScripts; - } - for (int i = 0; i < root.getChildNodes().getLength(); i++) { - ScriptConfig script = new ScriptConfig(); - script.parseXML((Element) root.getChildNodes().item(i)); - botScripts.add(script); - } - return botScripts; - } - - /** * downBotScript * @@ -1368,16 +1015,7 @@ public class SDKConnection { * @return types */ public String[] getTypes() { - return types; - } - - /** - * getChannelTypes - * - * @return channelTypes - */ - public String[] getChannelTypes() { - return channelTypes; + return types.clone(); } /** @@ -1386,7 +1024,7 @@ public class SDKConnection { * @return accessModes */ public String[] getAccessModes() { - return accessModes; + return accessModes.clone(); } /** @@ -1395,7 +1033,7 @@ public class SDKConnection { * @return mediaAccessModes */ public String[] getMediaAccessModes() { - return mediaAccessModes; + return mediaAccessModes.clone(); } /** @@ -1572,7 +1210,6 @@ public class SDKConnection { System.out.println("POST: " + url); System.out.println("XML: " + xml); } - String result = ""; Response response = null; try { ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), @@ -1581,19 +1218,21 @@ public class SDKConnection { .cookieJar(cookieJar) .build(); response = getResponse(okHttpClient, url, xml); - - if ((response.code() != 200) && (response.code() != 204)) { - this.exception = new SDKException(response.code() + ""); - throw this.exception; + if(response != null){ + if ((response.code() != 200) && (response.code() != 204)) { + this.exception = new SDKException(response.code() + ""); + throw this.exception; + } } } catch (Exception exception) { if (this.debug) { exception.printStackTrace(); } -// this.exception = new SDKException(exception); -// throw this.exception; } - return response.body().toString(); + if(response!=null){ + return response.body().toString(); + } + return null; } /** diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java index 73cc25030bb399c3371a4f8cb21b2fb9244263c7..250c50c52f7c3cccdff65d38dee73150b137b79a 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java @@ -27,7 +27,6 @@ import ohos.agp.components.DirectionalLayout; import ohos.agp.components.Image; import ohos.agp.components.LayoutScatter; import ohos.agp.components.ListContainer; -import ohos.agp.components.ScrollView; import ohos.agp.components.Text; import ohos.agp.components.TextField; import ohos.agp.utils.LayoutAlignment; @@ -69,7 +68,6 @@ import org.botlibre.sdk.MainAbility; import org.botlibre.sdk.ResourceTable; import org.botlibre.sdk.ability.adapter.EmoteAdapter; import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChatConfig; import org.botlibre.sdk.config.ChatResponse; import org.botlibre.sdk.config.InstanceConfig; @@ -79,7 +77,6 @@ import org.botlibre.sdk.util.FileUtils; import org.botlibre.sdk.util.LogUtils; import org.botlibre.sdk.util.PreferencesUtils; import org.botlibre.sdk.util.ResUtils; -import org.botlibre.sdk.util.ShapeUtils; import org.botlibre.sdk.util.TextStream; import org.botlibre.sdk.util.ToastUtils; @@ -91,7 +88,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Optional; -import java.util.Random; import java.util.UUID; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; @@ -100,26 +96,24 @@ import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; /** * Ability for chatting with a bot. * To launch this Ability from your app you can use the HttpFetchAction passing the bot id or name as a config, and launch=true. + * + * @since 2021-04-16 */ @SuppressWarnings("deprecation") public class ChatAbility extends LibreAbility { - private static final int BEGIN_LISTENING = 8; - private static final int ASR_RESULT = 9; private static final int BEGIN_SPEECH = 10; private static final int END_SPEECH = 11; private static final int AUTO_RESPONSE = 12; - protected static boolean DEBUG; - public DirectionalLayout emote_select; - public Image emoteSpinImage; - public Text emoteSpin; - public Button correctionButton; - public static Ability ability; - - private boolean isRecording; - public static boolean isListening; - - public static final int REQ_PERMISSION_CODE = 1003; + private static boolean DEBUG; + private DirectionalLayout emote_select; + private Image emoteSpinImage; + private Text emoteSpin; + private Button correctionButton; + private Ability ability; + private static boolean isListening; + + private static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( Arrays.asList( @@ -182,7 +176,7 @@ public class ChatAbility extends LibreAbility { } String key = dialogueMap.get(hello); - if (key != null && MainAbility.launchInstanceName.equals("Basic")) { + if (key != null && MainAbility.getLaunchInstanceName().equals("Basic")) { reply = key; } else { reply = hello; @@ -197,7 +191,7 @@ public class ChatAbility extends LibreAbility { } String key = dialogueMap.get(hello); - if (key != null && MainAbility.launchInstanceName.equals("Basic")) { + if (key != null && MainAbility.getLaunchInstanceName().equals("Basic")) { reply = key; } else { reply = hello; @@ -228,9 +222,9 @@ public class ChatAbility extends LibreAbility { * 语音识别客户端 */ private AsrClient asrClient; - public Component videoLayout; - public Image bigImage; - protected TextField editText; + private Component videoLayout; + private Image bigImage; + private TextField editText; private boolean volumeChecked = true; private Thread thread; @@ -250,18 +244,14 @@ public class ChatAbility extends LibreAbility { protected InstanceConfig instance; private int stateLayouts = 0; private ListContainer scrollView; - private ScrollView responseScroll; - public boolean music = false; - - private double lastReply = System.currentTimeMillis(); - public static List messages = new ArrayList(); - public ChatResponse response; - public Player audioPlayer; - public String currentAudio; + private static List messages = new ArrayList(); + private ChatResponse response; + private Player audioPlayer; + private String currentAudio; - public boolean videoError; - protected volatile boolean wasSpeaking; + private boolean videoError; + private volatile boolean wasSpeaking; private boolean active = true; @@ -269,21 +259,21 @@ public class ChatAbility extends LibreAbility { protected String avatarId; protected boolean changingVoice; Player speechPlayer; - protected Random random = new Random(); - - protected PixelMap icon; - //flag will check if the mic is ON or OFF - public static boolean micLastStat; - - private boolean failedOfflineLanguage = false; - private boolean threadIsOn = false; - + private static boolean micLastStat; private AudioCapturer mAudioCapturer; private boolean isFlag; private ChatListProvicer chatProvider; + public static boolean isDEBUG() { + return DEBUG; + } + + public static void setDEBUG(boolean DEBUG) { + ChatAbility.DEBUG = DEBUG; + } + /** * 文本转语音 语音播报 */ @@ -342,7 +332,7 @@ public class ChatAbility extends LibreAbility { @Override public void onEvent(int eventType, PacMap pacMap) { if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) { - VoiceConfig voice = MainAbility.voice; + VoiceConfig voice = MainAbility.getVoice(); float pitch = 1; if (voice != null && voice.pitch != null && voice.pitch.length() > 0) { try { @@ -414,7 +404,6 @@ public class ChatAbility extends LibreAbility { @Override public void onBeginningOfSpeech() { LogUtils.sop("onBeginningOfSpeech-当前线程:" + Thread.currentThread().getName()); - isRecording = true; mainHandler.sendEvent(BEGIN_SPEECH); } @@ -441,8 +430,6 @@ public class ChatAbility extends LibreAbility { */ @Override public void onEndOfSpeech() { - isRecording = false; - lastReply = System.currentTimeMillis(); LogUtils.sop("onSpeechFinish"); mainHandler.sendEvent(END_SPEECH); } @@ -455,8 +442,6 @@ public class ChatAbility extends LibreAbility { public void onError(int error) { LogUtils.sop("ChatActivity on error executes here!"); try { - isRecording = false; - if (error == AsrError.ERROR_AUDIO) { LogUtils.sop("Error: Audio Recording Error"); } else if (error == AsrError.ERROR_CLIENT) { @@ -470,7 +455,6 @@ public class ChatAbility extends LibreAbility { restartListening(); } else if (error == AsrError.ERROR_SERVER) { LogUtils.sop("Error: Server Error"); - failedOfflineLanguage = true; restartListening(); } else if (error == AsrError.ERROR_SPEECH_TIMEOUT) { LogUtils.sop("Error: NO speech input"); @@ -541,22 +525,11 @@ public class ChatAbility extends LibreAbility { @Override protected void onStart(Intent intent) { super.onStart(intent); -// if (MainAbility.current == null) { -// terminateAbility(); -// return; -// } -// if (MainAbility.instance == null || !(MainAbility.instance instanceof InstanceConfig)) { -// terminateAbility(); -// return; -// } super.setUIContent(ResourceTable.Layout_activity_chat); ability = this; - //clear the messages from the listView - messages.clear(); - - audioManager = new AudioManager(this); - if (MainAbility.sound) { + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); @@ -576,14 +549,14 @@ public class ChatAbility extends LibreAbility { } //For "scream" issue - micLastStat = MainAbility.listenInBackground; + micLastStat = MainAbility.isListenInBackground(); getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS); - this.instance = (InstanceConfig) MainAbility.instance; + this.instance = (InstanceConfig) MainAbility.getInstance(); tvTitle = ((Text) findComponentById(ResourceTable.Id_title)); imAvatar = (Image) findComponentById(ResourceTable.Id_icon); - tvTitle.setText(MainAbility.launchInstanceName); + tvTitle.setText(MainAbility.getLaunchInstanceName()); imAvatar.setPixelMap(ResourceTable.Media_bot); // if (MainAbility.online) { // HttpGetImageAction.fetchImage(this, this.instance.avatar, (Image) findComponentById(ResourceTable.Id_icon)); @@ -615,8 +588,6 @@ public class ChatAbility extends LibreAbility { emoteSpinImage = (Image) findComponentById(ResourceTable.Id_emoteSpinImage); emoteSpin = (Text) findComponentById(ResourceTable.Id_emoteSpin); correctionButton = (Button) findComponentById(ResourceTable.Id_correctionButton); - responseScroll = (ScrollView) findComponentById(ResourceTable.Id_responseScroll); - //responseScroll.setVisibility(Component.INVISIBLE); emoteSpin.setText("none"); @@ -653,9 +624,9 @@ public class ChatAbility extends LibreAbility { } }); - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { setMicIcon(false, false); - } else if (!MainAbility.listenInBackground) { + } else if (!MainAbility.isListenInBackground()) { setMicIcon(false, false); } // resetVideoErrorListener(); @@ -690,7 +661,7 @@ public class ChatAbility extends LibreAbility { } }); - if (MainAbility.translate) { + if (MainAbility.isTranslate()) { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); } else { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); @@ -707,7 +678,7 @@ public class ChatAbility extends LibreAbility { }); micButton.setClickedListener(component -> { - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { reqPermissions(); } else { ToastUtils.showCenterToast(ability, "Your device doesn't support Speech to Text"); @@ -783,7 +754,7 @@ public class ChatAbility extends LibreAbility { } else if (mClickcount == 2) { mSecondClick = System.currentTimeMillis(); if (mSecondClick - mFirstClick < 1000) { - boolean isVideo = !MainAbility.disableVideo && !videoError && response != null + boolean isVideo = !MainAbility.isDisableVideo() && !videoError && response != null && response.isVideo(); videoLayout = findComponentById(ResourceTable.Id_videoLayout); if (bigImage.getVisibility() == Component.VISIBLE) { @@ -825,7 +796,7 @@ public class ChatAbility extends LibreAbility { } }); - if (!MainAbility.online) { + if (!MainAbility.isOnline()) { // HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, this.bigImage); // HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, (Image) findComponentById(ResourceTable.Id_responseImageView)); // HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, findComponentById(ResourceTable.Id_icon)); @@ -838,21 +809,21 @@ public class ChatAbility extends LibreAbility { final ChatConfig config = new ChatConfig(); //config.instance = instance.id; config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; + config.avatarHD = MainAbility.isHd(); + config.speak = !MainAbility.isDeviceVoice(); } private List emoteitem; - public void emoteImage() { + private void emoteImage() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -918,7 +889,7 @@ public class ChatAbility extends LibreAbility { private TextField title; - public void submitContent() { + private void submitContent() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -952,11 +923,7 @@ public class ChatAbility extends LibreAbility { }); } - public void menuList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void menuList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_menu_chat, null, false); @@ -972,12 +939,12 @@ public class ChatAbility extends LibreAbility { Checkbox checkBox5 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox5); Checkbox checkBox6 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox6); Checkbox checkBox7 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox7); - checkBox1.setChecked(MainAbility.sound); - checkBox2.setChecked(MainAbility.deviceVoice); - checkBox3.setChecked(MainAbility.handsFreeSpeech); - checkBox5.setChecked(MainAbility.disableVideo || this.videoError); - checkBox6.setChecked(MainAbility.webm); - checkBox7.setChecked(MainAbility.hd); + checkBox1.setChecked(MainAbility.isSound()); + checkBox2.setChecked(MainAbility.isDeviceVoice()); + checkBox3.setChecked(MainAbility.isHandsFreeSpeech()); + checkBox5.setChecked(MainAbility.isDisableVideo() || this.videoError); + checkBox6.setChecked(MainAbility.isWebm()); + checkBox7.setChecked(MainAbility.isHd()); checkBox0.setClickable(false); checkBox1.setClickable(false); checkBox2.setClickable(false); @@ -1006,10 +973,10 @@ public class ChatAbility extends LibreAbility { toggleDisableVideo(); break; case ResourceTable.Id_menuItem6: - MainAbility.webm = !MainAbility.webm; + MainAbility.setWebm(!MainAbility.isWebm()); break; case ResourceTable.Id_menuItem7: - MainAbility.hd = !MainAbility.hd; + MainAbility.setHd(!MainAbility.isHd()); break; } menuDialog.hide(); @@ -1029,80 +996,22 @@ public class ChatAbility extends LibreAbility { menuDialog.show(); } - public void typeList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - - PopupDialog menuDialog = new PopupDialog(this, null); - DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) - .parse(ResourceTable.Layout_type_list, null, false); - menuDialog.setCustomComponent(menuComponent); - menuDialog.setSize((int) (ResUtils.getScreenWidth(this) * 0.8), - DirectionalLayout.LayoutConfig.MATCH_CONTENT); - menuDialog.showOnCertainPosition(LayoutAlignment.CENTER, 0, 0); - menuDialog.setAutoClosable(true); - Checkbox checkBox1 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox1); - Checkbox checkBox2 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox2); - Checkbox checkBox3 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox3); - Checkbox checkBox4 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox4); - checkBox1.setClickable(false); - checkBox2.setClickable(false); - checkBox3.setClickable(false); - checkBox4.setClickable(false); - Component.ClickedListener listener = component -> { - switch (component.getId()) { - case ResourceTable.Id_menuItem1: - messages.add(getMessage("pepperoni")); - break; - case ResourceTable.Id_menuItem2: - messages.add(getMessage("hawaiian")); - break; - case ResourceTable.Id_menuItem3: - messages.add(getMessage("vegetarian")); - break; - case ResourceTable.Id_menuItem4: - messages.add(getMessage("cheese")); - break; - } - type = 10; - mainHandler.sendEvent(AUTO_RESPONSE); - chatProvider.notifyDataChanged(); - menuDialog.hide(); - menuDialog.remove(); - }; - - menuComponent.findComponentById(ResourceTable.Id_menuItem1).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem2).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem3).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem4).setClickedListener(listener); - menuDialog.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.BOTTOM); - menuDialog.show(); - } - - public void exitDialog() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - - CommonDialog menuDialog = new CommonDialog(this); + private void exitDialog() { + final CommonDialog menuDialog = new CommonDialog(this); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_exit_dialog, null, false); menuDialog.setContentCustomComponent(menuComponent); menuDialog.setSize((int) (ResUtils.getScreenWidth(this) * 0.8), DirectionalLayout.LayoutConfig.MATCH_CONTENT); - //menuDialog.showOnCertainPosition(LayoutAlignment.CENTER, 0, 0); menuDialog.setAutoClosable(true); Component.ClickedListener listener = component -> { switch (component.getId()) { case ResourceTable.Id_button1: + case ResourceTable.Id_button3: terminateAbility(); break; case ResourceTable.Id_button2: break; - case ResourceTable.Id_button3: - terminateAbility(); - break; } menuDialog.hide(); menuDialog.remove(); @@ -1115,24 +1024,24 @@ public class ChatAbility extends LibreAbility { } - public void flagResponse() { + private void flagResponse() { MainAbility.confirm("Flag bad response?", this, true, (iDialog, i) -> { switch (i) { case IDialog.BUTTON1: ChatConfig config = new ChatConfig(); //config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); config.message = "flag"; //text.getText().toString().trim(); if (config.message.equals("")) { @@ -1167,22 +1076,22 @@ public class ChatAbility extends LibreAbility { return config; } - public void submitChat() { + private void submitChat() { ChatConfig config = new ChatConfig(); - config.instance = MainAbility.launchInstanceId; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.instance = MainAbility.getLaunchInstanceId(); + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = this.avatarId; config.emote = "None"; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); if (inputType == 1) { config.message = editText.getText().trim(); @@ -1230,12 +1139,11 @@ public class ChatAbility extends LibreAbility { // stopListening(); //its Important for "sleep" "scream" ...etc commands. //this will turn off the mic - MainAbility.listenInBackground = false; + MainAbility.setListenInBackground(false); } - public void toggleSound() { - MainAbility.sound = !MainAbility.sound; - if (MainAbility.sound) { + private void toggleSound() { + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); @@ -1243,76 +1151,46 @@ public class ChatAbility extends LibreAbility { resetToolbar(); } - public void toggleHandsFreeSpeech() { - MainAbility.handsFreeSpeech = !MainAbility.handsFreeSpeech; - if (!MainAbility.handsFreeSpeech) { + private void toggleHandsFreeSpeech() { + MainAbility.setHandsFreeSpeech(!MainAbility.isHandsFreeSpeech()); + if (!MainAbility.isHandsFreeSpeech()) { stopListening(); - } else if (MainAbility.handsFreeSpeech) { + } else if (MainAbility.isHandsFreeSpeech()) { beginListening(); } Preferences cookies = PreferencesUtils.getPreferences(this.ability); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); cookies.flushSync(); } - public void toggleDisableVideo() { + private void toggleDisableVideo() { if (this.videoError) { this.videoError = false; - MainAbility.disableVideo = false; - } else { - MainAbility.disableVideo = !MainAbility.disableVideo; - } - } - - public void changeAvatar() { - if (MainAbility.online) { - MainAbility.browsing = true; - BrowseConfig config = new BrowseConfig(); - config.type = "Avatar"; - config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; -// HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); + MainAbility.setDisableVideo(false); } else { -// Intent intent = getIntent(ability, AvatarSelection.class.getName()); -// startAbility(intent); + MainAbility.setDisableVideo(!MainAbility.isDisableVideo()); } } - public void changeVoice() { - this.changingVoice = true; -// Intent intent = getIntent(ability, ChangeVoiceAbility.class.getName()); -// startAbility(intent); + private void toggleDeviceVoice() { + MainAbility.setDeviceVoice(!MainAbility.isDeviceVoice()); } - public void toggleDeviceVoice() { - MainAbility.deviceVoice = !MainAbility.deviceVoice; - } - - public void toggleFlag(Component view) { - flagResponse(); - } - - - public void resetToolbar() { - if (MainAbility.sound) { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_sound); + private void resetToolbar() { + if (MainAbility.isSound()) { + ResUtils.setBackground(soundButton, ResourceTable.Media_sound); } else { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_mute); + ResUtils.setBackground(soundButton, ResourceTable.Media_mute); } } @Override public void onActive() { - MainAbility.searching = false; - MainAbility.searchingPosts = false; - if (MainAbility.browsing && (MainAbility.instance instanceof AvatarConfig)) { - if (MainAbility.user == null || MainAbility.user.type == null || MainAbility.user.type.isEmpty() || MainAbility.user.type.equals("Basic")) { - //MainAbility.showMessage("You must upgrade to get access to this avatar", this); - //super.onResume(); - //return; - } - this.avatar = (AvatarConfig) MainAbility.instance; + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + if (MainAbility.isBrowsing() && (MainAbility.getInstance() instanceof AvatarConfig)) { + + this.avatar = (AvatarConfig) MainAbility.getInstance(); this.avatarId = this.avatar.id; if (this.bigImage.getVisibility() == Component.HIDE) { this.bigImage.setVisibility(Component.VISIBLE); @@ -1327,8 +1205,8 @@ public class ChatAbility extends LibreAbility { // HttpFetchChatAvatarAction action = new HttpFetchChatAvatarAction(this, avatarConfig); // action.execute(); } - MainAbility.browsing = false; - if ((MainAbility.instance instanceof InstanceConfig) && MainAbility.instance.id.equals(this.instance.id)) { + MainAbility.setBrowsing(false); + if ((MainAbility.getInstance() instanceof InstanceConfig) && MainAbility.getInstance().id.equals(this.instance.id)) { //this.instance = (InstanceConfig) MainAbility.instance; } else { //MainAbility.instance = this.instance; @@ -1341,7 +1219,7 @@ public class ChatAbility extends LibreAbility { super.onActive(); } - public void resetTTS() { + private void resetTTS() { ttsClient.stopSpeak(); ttsClient.release(); ttsClient.destroy(); @@ -1354,7 +1232,7 @@ public class ChatAbility extends LibreAbility { } } - public String getAvatarIcon(ChatResponse config) { + private String getAvatarIcon(ChatResponse config) { if (this.avatar != null) { return this.avatar.avatar; } @@ -1364,10 +1242,10 @@ public class ChatAbility extends LibreAbility { return config.avatar; } - public void resetAvatar(AvatarConfig config) { + private void resetAvatar(AvatarConfig config) { } - public void micConfiguration() { + private void micConfiguration() { Intent intent = getIntent(ability, MicConfigAbility.class.getName()); startAbility(intent); terminateAbility(); @@ -1386,7 +1264,7 @@ public class ChatAbility extends LibreAbility { if (this.instance != null) { ChatConfig config = new ChatConfig(); //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; + config.conversation = MainAbility.getConversation(); config.disconnect = true; // HttpChatAction action = new HttpChatAction(this, config); @@ -1484,7 +1362,7 @@ public class ChatAbility extends LibreAbility { return html; } - public void response(final ChatResponse response) { + private void response(final ChatResponse response) { if (speechPlayer != null || ttsClient != null) { try { ttsClient.stopSpeak(); @@ -1514,16 +1392,11 @@ public class ChatAbility extends LibreAbility { status = status + response.pose; } LogUtils.sop("response.command: " + response.command); - if (response.command != null) { - ZSONObject jsonObject = response.getCommand(); - //Command command = new Command(this, jsonObject); - } Text statusView = (Text) findComponentById(ResourceTable.Id_statusText); statusView.setText(status); final String text = response.message; if (text == null) { - beginListening(); return; } @@ -1533,27 +1406,11 @@ public class ChatAbility extends LibreAbility { if (stateLayouts == 3 || stateLayouts == 4) { ToastUtils.show(ability, html); } - if (html.contains("<") && html.contains(">")) { - html = linkPostbacks(html); - } - - boolean talk = (text.trim().length() > 0) && (MainAbility.deviceVoice || (this.response.speech != null && this.response.speech.length() > 0)); - if (MainAbility.sound && talk) { - if (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { - } else if (talk) { - - } - } else if (talk && (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.avatarTalk != null)) { - - - } else { - //handler.sendEvent(BEGIN_LISTENING); - } } catch (Exception exception) { LogUtils.sop(exception.getMessage()); } if (micLastStat) { - MainAbility.listenInBackground = true; + MainAbility.setListenInBackground(true); } } @@ -1590,9 +1447,8 @@ public class ChatAbility extends LibreAbility { } private void restartListening() { - lastReply = System.currentTimeMillis(); debug("restartListening"); - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { return; } if (!isListening) { @@ -1602,7 +1458,7 @@ public class ChatAbility extends LibreAbility { } - public void scanBarcode(Component v) { + private void scanBarcode(Component v) { // IntentIntegrator integrator = new IntentIntegrator(this); // integrator.initiateScan(); } @@ -1618,7 +1474,7 @@ public class ChatAbility extends LibreAbility { } - public void debug(final String text) { + private void debug(final String text) { if (!DEBUG) { return; } @@ -1632,16 +1488,16 @@ public class ChatAbility extends LibreAbility { private void muteMicBeep(boolean mute) { - debug("muteMicBeep:" + mute + ":" + MainAbility.volume); + debug("muteMicBeep:" + mute + ":" + MainAbility.getVolume()); AudioManager audioManager = new AudioManager(ability); if (mute) { LogUtils.sop("muteMicBeep : " + 0); //if its true then the Volume will be zero. audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } else { - LogUtils.sop("muteMicBeep : " + MainAbility.volume); + LogUtils.sop("muteMicBeep : " + MainAbility.getVolume()); //if its false, the Volume will put back on - audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.volume); + audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.getVolume()); } } @@ -1656,24 +1512,23 @@ public class ChatAbility extends LibreAbility { if (volume != 0) { debug("setStreamVolume:" + volume); LogUtils.sop("setStreamVolume : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } private void beginListening() { - this.lastReply = System.currentTimeMillis(); setStreamVolume(); debug("beginListening:"); try { - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { return; } - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { muteMicBeep(true); isListening = true; } - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { muteMicBeep(false); return; } @@ -1694,7 +1549,7 @@ public class ChatAbility extends LibreAbility { } - public void setAudio() { + private void setAudio() { AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder() .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT) .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_IN_MONO) diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility2.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility2.java index 105881e11319a0fccc626e2b13c154f7e457900d..9d8ae86cd9137ae247fcc991c91dd04af8baa952 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility2.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility2.java @@ -70,7 +70,6 @@ import org.botlibre.sdk.ResourceTable; import org.botlibre.sdk.ability.adapter.CommandAdapter; import org.botlibre.sdk.ability.adapter.EmoteAdapter; import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChatConfig; import org.botlibre.sdk.config.ChatResponse; import org.botlibre.sdk.config.InstanceConfig; @@ -80,8 +79,6 @@ import org.botlibre.sdk.util.ApplicationJumpUtil; import org.botlibre.sdk.util.LogUtils; import org.botlibre.sdk.util.PreferencesUtils; import org.botlibre.sdk.util.ResUtils; -import org.botlibre.sdk.util.ShapeUtils; -import org.botlibre.sdk.util.StringUtils; import org.botlibre.sdk.util.TextStream; import org.botlibre.sdk.util.ToastUtils; @@ -92,7 +89,6 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Optional; -import java.util.Random; import java.util.UUID; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; @@ -101,26 +97,26 @@ import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; /** * Ability for chatting with a bot. * To launch this Ability from your app you can use the HttpFetchAction passing the bot id or name as a config, and launch=true. + * + * @since 2021-04-16 */ @SuppressWarnings("deprecation") public class ChatAbility2 extends LibreAbility { - private static final int BEGIN_LISTENING = 8; - private static final int ASR_RESULT = 9; private static final int BEGIN_SPEECH = 10; private static final int END_SPEECH = 11; private static final int AUTO_RESPONSE = 12; - protected static boolean DEBUG; - public DirectionalLayout emote_select; - public Image emoteSpinImage; - public Text emoteSpin; - public Button correctionButton; - public static Ability ability; + private static boolean DEBUG; + private DirectionalLayout emote_select; + private Image emoteSpinImage; + private Text emoteSpin; + private Button correctionButton; + private static Ability ability; private boolean isRecording; - public static boolean isListening; + private static boolean isListening; - public static final int REQ_PERMISSION_CODE = 1003; + private static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( Arrays.asList( @@ -389,7 +385,7 @@ public class ChatAbility2 extends LibreAbility { ApplicationJumpUtil.setSystemOption(this, IntentConstants.ACTION_DIAL); // 启动电话 break; case "wechat": - reply = "Opening " + StringUtils.toUpperFirstCode(msg); + reply = "Opening " + ResUtils.toUpperFirstCode(msg); //打开微信 break; case "bye": @@ -441,8 +437,7 @@ public class ChatAbility2 extends LibreAbility { reply = "Bon nuit."; break; case "firefox": - reply = "Opening " + StringUtils.toUpperFirstCode(msg); - //ApplicationJumpUtil.startAppFromPackageName(this,"com.example.recyclerviewswipedismiss"); // 通过包名调用应用 + reply = "Opening " + ResUtils.toUpperFirstCode(msg); ApplicationJumpUtil.startAppFromPackageName(this, "com.example.summaryjs"); // 通过包名调用应用 break; default: @@ -460,8 +455,8 @@ public class ChatAbility2 extends LibreAbility { * 语音识别客户端 */ private AsrClient asrClient; - public Component videoLayout; - public Image bigImage; + private Component videoLayout; + private Image bigImage; protected TextField editText; private boolean volumeChecked = true; private Thread thread; @@ -483,16 +478,16 @@ public class ChatAbility2 extends LibreAbility { private int stateLayouts = 0; private ListContainer scrollView; private ScrollView responseScroll; - public boolean music = false; + private boolean music = false; private double lastReply = System.currentTimeMillis(); - public static List messages = new ArrayList(); - public ChatResponse response; - public Player audioPlayer; - public String currentAudio; + private static List messages = new ArrayList(); + private ChatResponse response; + private Player audioPlayer; + private String currentAudio; - public boolean videoError; + private boolean videoError; protected volatile boolean wasSpeaking; private boolean active = true; @@ -501,17 +496,8 @@ public class ChatAbility2 extends LibreAbility { protected String avatarId; protected boolean changingVoice; Player speechPlayer; - protected Random random = new Random(); - - protected PixelMap icon; - - //flag will check if the mic is ON or OFF - public static boolean micLastStat; - - private boolean failedOfflineLanguage = false; - private boolean threadIsOn = false; - + private static boolean micLastStat; private AudioCapturer mAudioCapturer; private boolean isFlag; private ChatListProvicer chatProvider; @@ -549,13 +535,7 @@ public class ChatAbility2 extends LibreAbility { public void onFinish(String s) { //handler.sendEvent(BEGIN_LISTENING); try { -// if (!MainAbility.disableVideo && !videoError && this.response.isVideo()) { -// this.videoView.post(new Runnable() { -// public void run() { -// cycleVideo(response); -// } -// }); -// } + } catch (Exception exception) { LogUtils.sop(exception.toString()); } @@ -574,7 +554,7 @@ public class ChatAbility2 extends LibreAbility { @Override public void onEvent(int eventType, PacMap pacMap) { if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) { - VoiceConfig voice = MainAbility.voice; + VoiceConfig voice = MainAbility.getVoice(); float pitch = 1; if (voice != null && voice.pitch != null && voice.pitch.length() > 0) { try { @@ -627,6 +607,14 @@ public class ChatAbility2 extends LibreAbility { } }; + public static Ability getAbility() { + return ability; + } + + public static void setAbility(Ability ability) { + ChatAbility2.ability = ability; + } + /** * 语音识别 */ @@ -702,7 +690,6 @@ public class ChatAbility2 extends LibreAbility { restartListening(); } else if (error == AsrError.ERROR_SERVER) { LogUtils.sop("Error: Server Error"); - failedOfflineLanguage = true; restartListening(); } else if (error == AsrError.ERROR_SPEECH_TIMEOUT) { LogUtils.sop("Error: NO speech input"); @@ -773,61 +760,28 @@ public class ChatAbility2 extends LibreAbility { @Override protected void onStart(Intent intent) { super.onStart(intent); -// if (MainAbility.current == null) { -// terminateAbility(); -// return; -// } -// if (MainAbility.instance == null || !(MainAbility.instance instanceof InstanceConfig)) { -// terminateAbility(); -// return; -// } super.setUIContent(ResourceTable.Layout_activity_chat2); - ability = this; - //clear the messages from the listView - + setAbility(this); messages.clear(); - - audioManager = new AudioManager(this); - if (MainAbility.sound) { + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } dialogueMap = new HashMap<>(); -// try { -// ResourceManager resManager = getResourceManager(); -// RawFileEntry rawFile = resManager.getRawFileEntry("resources/rawfile/basic.json"); -// jsonStr = FileUtils.convertStreamToString(rawFile.openRawFile()); -// ZSONArray ary = ZSONArray.stringToZSONArray(jsonStr); -// for (int i = 0; i < ary.size(); i++) { -// ZSONObject obj = ZSONObject.classToZSON(ary.get(i)); -// dialogueMap.put(obj.getString("que"), obj.getString("ans")); -// } -// } catch (IOException e) { -// e.printStackTrace(); -// } - //For "scream" issue - micLastStat = MainAbility.listenInBackground; + micLastStat = MainAbility.isListenInBackground(); getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS); - this.instance = (InstanceConfig) MainAbility.instance; + this.instance = (InstanceConfig) MainAbility.getInstance(); tvTitle = ((Text) findComponentById(ResourceTable.Id_title)); imAvatar = (Image) findComponentById(ResourceTable.Id_icon); - tvTitle.setText(MainAbility.launchInstanceName); + tvTitle.setText(MainAbility.getLaunchInstanceName()); imAvatar.setPixelMap(ResourceTable.Media_bot); -// if (MainAbility.online) { -// HttpGetImageAction.fetchImage(this, this.instance.avatar, (Image) findComponentById(ResourceTable.Id_icon)); -// } ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); - - //Last time will be saved for the MIC. -// if (MainAbility.listenInBackground && MainAbility.handsFreeSpeech) { -// microphoneThread(thread); -// } - //scrollVie added and stuff scrollView = (ListContainer) findComponentById(ResourceTable.Id_chatList); menuMLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_menuMLayout); @@ -850,9 +804,6 @@ public class ChatAbility2 extends LibreAbility { emoteSpin = (Text) findComponentById(ResourceTable.Id_emoteSpin); correctionButton = (Button) findComponentById(ResourceTable.Id_correctionButton); responseScroll = (ScrollView) findComponentById(ResourceTable.Id_responseScroll); - - //responseScroll.setVisibility(Component.INVISIBLE); - emoteSpin.setText("none"); emoteSpinImage.setPixelMap(ResourceTable.Media_emote); @@ -900,9 +851,9 @@ public class ChatAbility2 extends LibreAbility { } }); - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { setMicIcon(false, false); - } else if (!MainAbility.listenInBackground) { + } else if (!MainAbility.isListenInBackground()) { setMicIcon(false, false); } // resetVideoErrorListener(); @@ -937,7 +888,7 @@ public class ChatAbility2 extends LibreAbility { } }); - if (MainAbility.translate) { + if (MainAbility.isTranslate()) { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); } else { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); @@ -954,7 +905,7 @@ public class ChatAbility2 extends LibreAbility { }); micButton.setClickedListener(component -> { - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { reqPermissions(); } else { ToastUtils.showCenterToast(ability, "Your device doesn't support Speech to Text"); @@ -1030,7 +981,7 @@ public class ChatAbility2 extends LibreAbility { } else if (mClickcount == 2) { mSecondClick = System.currentTimeMillis(); if (mSecondClick - mFirstClick < 1000) { - boolean isVideo = !MainAbility.disableVideo && !videoError && response != null + boolean isVideo = !MainAbility.isDisableVideo() && !videoError && response != null && response.isVideo(); videoLayout = findComponentById(ResourceTable.Id_videoLayout); if (bigImage.getVisibility() == Component.VISIBLE) { @@ -1072,35 +1023,25 @@ public class ChatAbility2 extends LibreAbility { } }); - if (!MainAbility.online) { -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, this.bigImage); -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, (Image) findComponentById(ResourceTable.Id_responseImageView)); -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, findComponentById(ResourceTable.Id_icon)); - } else { - //HttpGetImageAction.fetchImage(this, this.instance.avatar, imAvatar); - //HttpGetImageAction.fetchImage(this, instance.avatar, this.bigImage); - //HttpGetImageAction.fetchImage(this, instance.avatar, (Image) findComponentById(ResourceTable.Id_responseImageView)); - } - final ChatConfig config = new ChatConfig(); //config.instance = instance.id; config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; + config.avatarHD = MainAbility.isHd(); + config.speak = !MainAbility.isDeviceVoice(); } private List emoteitem; private List command; - public void commandList() { + private void commandList() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -1182,7 +1123,7 @@ public class ChatAbility2 extends LibreAbility { }); } - public void emoteImage() { + private void emoteImage() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -1248,7 +1189,7 @@ public class ChatAbility2 extends LibreAbility { private TextField title; - public void availableDialog() { + private void availableDialog() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -1270,7 +1211,7 @@ public class ChatAbility2 extends LibreAbility { } - public void submitContent() { + private void submitContent() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -1304,11 +1245,7 @@ public class ChatAbility2 extends LibreAbility { }); } - public void menuList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void menuList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_menu_chat, null, false); @@ -1324,12 +1261,12 @@ public class ChatAbility2 extends LibreAbility { Checkbox checkBox5 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox5); Checkbox checkBox6 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox6); Checkbox checkBox7 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox7); - checkBox1.setChecked(MainAbility.sound); - checkBox2.setChecked(MainAbility.deviceVoice); - checkBox3.setChecked(MainAbility.handsFreeSpeech); - checkBox5.setChecked(MainAbility.disableVideo || this.videoError); - checkBox6.setChecked(MainAbility.webm); - checkBox7.setChecked(MainAbility.hd); + checkBox1.setChecked(MainAbility.isSound()); + checkBox2.setChecked(MainAbility.isDeviceVoice()); + checkBox3.setChecked(MainAbility.isHandsFreeSpeech()); + checkBox5.setChecked(MainAbility.isDisableVideo() || this.videoError); + checkBox6.setChecked(MainAbility.isWebm()); + checkBox7.setChecked(MainAbility.isHd()); checkBox0.setClickable(false); checkBox1.setClickable(false); checkBox2.setClickable(false); @@ -1358,10 +1295,10 @@ public class ChatAbility2 extends LibreAbility { toggleDisableVideo(); break; case ResourceTable.Id_menuItem6: - MainAbility.webm = !MainAbility.webm; + MainAbility.setWebm(!MainAbility.isWebm()); break; case ResourceTable.Id_menuItem7: - MainAbility.hd = !MainAbility.hd; + MainAbility.setHd(!MainAbility.isHd()); break; } menuDialog.hide(); @@ -1381,62 +1318,7 @@ public class ChatAbility2 extends LibreAbility { menuDialog.show(); } - public void typeList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - - PopupDialog menuDialog = new PopupDialog(this, null); - DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) - .parse(ResourceTable.Layout_type_list, null, false); - menuDialog.setCustomComponent(menuComponent); - menuDialog.setSize((int) (ResUtils.getScreenWidth(this) * 0.8), - DirectionalLayout.LayoutConfig.MATCH_CONTENT); - menuDialog.showOnCertainPosition(LayoutAlignment.CENTER, 0, 0); - menuDialog.setAutoClosable(true); - Checkbox checkBox1 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox1); - Checkbox checkBox2 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox2); - Checkbox checkBox3 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox3); - Checkbox checkBox4 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox4); - checkBox1.setClickable(false); - checkBox2.setClickable(false); - checkBox3.setClickable(false); - checkBox4.setClickable(false); - Component.ClickedListener listener = component -> { - switch (component.getId()) { - case ResourceTable.Id_menuItem1: - messages.add(getMessage("pepperoni")); - break; - case ResourceTable.Id_menuItem2: - messages.add(getMessage("hawaiian")); - break; - case ResourceTable.Id_menuItem3: - messages.add(getMessage("vegetarian")); - break; - case ResourceTable.Id_menuItem4: - messages.add(getMessage("cheese")); - break; - } - type = 10; - mainHandler.sendEvent(AUTO_RESPONSE); - chatProvider.notifyDataChanged(); - menuDialog.hide(); - menuDialog.remove(); - }; - - menuComponent.findComponentById(ResourceTable.Id_menuItem1).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem2).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem3).setClickedListener(listener); - menuComponent.findComponentById(ResourceTable.Id_menuItem4).setClickedListener(listener); - menuDialog.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.BOTTOM); - menuDialog.show(); - } - - public void exitDialog() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void exitDialog() { CommonDialog menuDialog = new CommonDialog(this); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_exit_dialog, null, false); @@ -1467,24 +1349,24 @@ public class ChatAbility2 extends LibreAbility { } - public void flagResponse() { + private void flagResponse() { MainAbility.confirm("Flag bad response?", this, true, (iDialog, i) -> { switch (i) { case IDialog.BUTTON1: ChatConfig config = new ChatConfig(); //config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); config.message = "flag"; //text.getText().toString().trim(); if (config.message.equals("")) { @@ -1519,22 +1401,22 @@ public class ChatAbility2 extends LibreAbility { return config; } - public void submitChat() { + private void submitChat() { ChatConfig config = new ChatConfig(); - config.instance = MainAbility.launchInstanceId; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.instance = MainAbility.getLaunchInstanceId(); + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = this.avatarId; config.emote = "None"; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); if (inputType == 1) { config.message = editText.getText().trim(); @@ -1554,16 +1436,8 @@ public class ChatAbility2 extends LibreAbility { mainHandler.sendEvent(AUTO_RESPONSE); }); }); -// -// HttpChatAction action = new HttpChatAction(ChatAbility2.this, config); -// action.execute(); resetToolbar(); - type = 10; - //mainHandler.sendEvent(AUTO_RESPONSE); -// webView.load("http://www.baidu.com"); - //webView.load(null, "thinking...", "text/html", "utf-8", null); - //Check the volume AudioManager audioManager = new AudioManager(ability); int volume = 0; @@ -1582,12 +1456,11 @@ public class ChatAbility2 extends LibreAbility { // stopListening(); //its Important for "sleep" "scream" ...etc commands. //this will turn off the mic - MainAbility.listenInBackground = false; + MainAbility.setListenInBackground(false); } - public void toggleSound() { - MainAbility.sound = !MainAbility.sound; - if (MainAbility.sound) { + private void toggleSound() { + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); @@ -1595,76 +1468,45 @@ public class ChatAbility2 extends LibreAbility { resetToolbar(); } - public void toggleHandsFreeSpeech() { - MainAbility.handsFreeSpeech = !MainAbility.handsFreeSpeech; - if (!MainAbility.handsFreeSpeech) { + private void toggleHandsFreeSpeech() { + MainAbility.setHandsFreeSpeech(!MainAbility.isHandsFreeSpeech()); + if (!MainAbility.isHandsFreeSpeech()) { stopListening(); - } else if (MainAbility.handsFreeSpeech) { + } else if (MainAbility.isHandsFreeSpeech()) { beginListening(); } Preferences cookies = PreferencesUtils.getPreferences(this.ability); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); cookies.flushSync(); } - public void toggleDisableVideo() { + private void toggleDisableVideo() { if (this.videoError) { this.videoError = false; - MainAbility.disableVideo = false; - } else { - MainAbility.disableVideo = !MainAbility.disableVideo; - } - } - - public void changeAvatar() { - if (MainAbility.online) { - MainAbility.browsing = true; - BrowseConfig config = new BrowseConfig(); - config.type = "Avatar"; - config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; -// HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); + MainAbility.setDisableVideo(false); } else { -// Intent intent = getIntent(ability, AvatarSelection.class.getName()); -// startAbility(intent); + MainAbility.setDisableVideo(!MainAbility.isDisableVideo()); } } - public void changeVoice() { - this.changingVoice = true; -// Intent intent = getIntent(ability, ChangeVoiceAbility.class.getName()); -// startAbility(intent); - } - - public void toggleDeviceVoice() { - MainAbility.deviceVoice = !MainAbility.deviceVoice; - } - - public void toggleFlag(Component view) { - flagResponse(); + private void toggleDeviceVoice() { + MainAbility.setDeviceVoice(!MainAbility.isDeviceVoice()); } - - public void resetToolbar() { - if (MainAbility.sound) { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_sound); + private void resetToolbar() { + if (MainAbility.isSound()) { + ResUtils.setBackground(soundButton, ResourceTable.Media_sound); } else { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_mute); + ResUtils.setBackground(soundButton, ResourceTable.Media_mute); } } @Override public void onActive() { - MainAbility.searching = false; - MainAbility.searchingPosts = false; - if (MainAbility.browsing && (MainAbility.instance instanceof AvatarConfig)) { - if (MainAbility.user == null || MainAbility.user.type == null || MainAbility.user.type.isEmpty() || MainAbility.user.type.equals("Basic")) { - //MainAbility.showMessage("You must upgrade to get access to this avatar", this); - //super.onResume(); - //return; - } - this.avatar = (AvatarConfig) MainAbility.instance; + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + if (MainAbility.isBrowsing() && (MainAbility.getInstance() instanceof AvatarConfig)) { + this.avatar = (AvatarConfig) MainAbility.getInstance(); this.avatarId = this.avatar.id; if (this.bigImage.getVisibility() == Component.HIDE) { this.bigImage.setVisibility(Component.VISIBLE); @@ -1673,27 +1515,16 @@ public class ChatAbility2 extends LibreAbility { this.videoLayout.setVisibility(Component.HIDE); } -// HttpGetImageAction.fetchImage(this, this.avatar.avatar, this.bigImage); - - AvatarConfig avatarConfig = (AvatarConfig) this.avatar.credentials(); -// HttpFetchChatAvatarAction action = new HttpFetchChatAvatarAction(this, avatarConfig); -// action.execute(); - } - MainAbility.browsing = false; - if ((MainAbility.instance instanceof InstanceConfig) && MainAbility.instance.id.equals(this.instance.id)) { - //this.instance = (InstanceConfig) MainAbility.instance; - } else { - //MainAbility.instance = this.instance; } + MainAbility.setBrowsing(false); if (this.changingVoice) { this.changingVoice = false; - //resetTTS(); } resetTTS(); super.onActive(); } - public void resetTTS() { + private void resetTTS() { ttsClient.stopSpeak(); ttsClient.release(); ttsClient.destroy(); @@ -1706,7 +1537,7 @@ public class ChatAbility2 extends LibreAbility { } } - public String getAvatarIcon(ChatResponse config) { + private String getAvatarIcon(ChatResponse config) { if (this.avatar != null) { return this.avatar.avatar; } @@ -1716,10 +1547,7 @@ public class ChatAbility2 extends LibreAbility { return config.avatar; } - public void resetAvatar(AvatarConfig config) { - } - - public void micConfiguration() { + private void micConfiguration() { Intent intent = getIntent(ability, MicConfigAbility.class.getName()); startAbility(intent); terminateAbility(); @@ -1737,12 +1565,8 @@ public class ChatAbility2 extends LibreAbility { } if (this.instance != null) { ChatConfig config = new ChatConfig(); - //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; + config.conversation = MainAbility.getConversation(); config.disconnect = true; - -// HttpChatAction action = new HttpChatAction(this, config); -// action.execute(); } //muteMicBeep(false); if (ttsClient != null) { @@ -1836,7 +1660,7 @@ public class ChatAbility2 extends LibreAbility { return html; } - public void response(final ChatResponse response) { + private void response(final ChatResponse response) { if (speechPlayer != null || ttsClient != null) { try { ttsClient.stopSpeak(); @@ -1868,51 +1692,24 @@ public class ChatAbility2 extends LibreAbility { status = status + response.pose; } LogUtils.sop("response.command: " + response.command); - if (response.command != null) { - ZSONObject jsonObject = response.getCommand(); - //Command command = new Command(this, jsonObject); - } Text statusView = (Text) findComponentById(ResourceTable.Id_statusText); statusView.setText(status); - final String text = response.message; if (text == null) { - //listContainer.invalidateViews(); -// if (listContainer.getChildCount() > 2) { -// listContainer.setSelection(list.getCount() - 2); -// } beginListening(); return; } messages.add(response); chatProvider.notifyDataChanged(); -// listContainer.invalidateViews(); -// if (listContainer.getCount() > 2) { -// listContainer.setSelection(list.getCount() - 2); -// } - String html = "";//Utils.linkHTML(text) if (stateLayouts == 3 || stateLayouts == 4) { ToastUtils.show(ability, html); } - if (html.contains("<") && html.contains(">")) { - html = linkPostbacks(html); - } - - boolean talk = (text.trim().length() > 0) && (MainAbility.deviceVoice || (this.response.speech != null && this.response.speech.length() > 0)); - if (MainAbility.sound && talk) { - if (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { - } else if (talk) { - } - } else if (talk && (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.avatarTalk != null)) { - - } else { - } } catch (Exception exception) { LogUtils.sop(exception.getMessage()); } if (micLastStat) { - MainAbility.listenInBackground = true; + MainAbility.setListenInBackground(true); } } @@ -1950,7 +1747,7 @@ public class ChatAbility2 extends LibreAbility { private void restartListening() { lastReply = System.currentTimeMillis(); debug("restartListening"); - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { return; } if (!isListening) { @@ -1960,7 +1757,7 @@ public class ChatAbility2 extends LibreAbility { } - public void scanBarcode(Component v) { + private void scanBarcode(Component v) { // IntentIntegrator integrator = new IntentIntegrator(this); // integrator.initiateScan(); } @@ -1976,7 +1773,7 @@ public class ChatAbility2 extends LibreAbility { } - public void debug(final String text) { + private void debug(final String text) { if (!DEBUG) { return; } @@ -1990,16 +1787,16 @@ public class ChatAbility2 extends LibreAbility { private void muteMicBeep(boolean mute) { - debug("muteMicBeep:" + mute + ":" + MainAbility.volume); + debug("muteMicBeep:" + mute + ":" + MainAbility.getVolume()); AudioManager audioManager = new AudioManager(ability); if (mute) { LogUtils.sop("muteMicBeep : " + 0); //if its true then the Volume will be zero. audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } else { - LogUtils.sop("muteMicBeep : " + MainAbility.volume); + LogUtils.sop("muteMicBeep : " + MainAbility.getVolume()); //if its false, the Volume will put back on - audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.volume); + audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.getVolume()); } } @@ -2014,7 +1811,7 @@ public class ChatAbility2 extends LibreAbility { if (volume != 0) { debug("setStreamVolume:" + volume); LogUtils.sop("setStreamVolume : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -2023,15 +1820,15 @@ public class ChatAbility2 extends LibreAbility { setStreamVolume(); debug("beginListening:"); try { - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { return; } - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { muteMicBeep(true); isListening = true; } - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { muteMicBeep(false); return; } @@ -2052,7 +1849,7 @@ public class ChatAbility2 extends LibreAbility { } - public void setAudio() { + private void setAudio() { AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder() .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT) .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_IN_MONO) diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java index a27cd18b1299f79d087d4d640da74ea508ca3cc2..3c8929ebe387933cbce918f94d10e4f3103df58a 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java @@ -19,9 +19,7 @@ package org.botlibre.sdk.ability; import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpCreateUserAction; import org.botlibre.sdk.config.UserConfig; -import org.botlibre.sdk.util.ResUtil; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Checkbox; @@ -29,16 +27,18 @@ import ohos.agp.components.Component; import ohos.agp.components.ComponentState; import ohos.agp.components.TextField; import ohos.agp.components.element.StateElement; +import org.botlibre.sdk.util.ResUtils; /** * Ability for creating a new user. + * + * @since 2021-04-16 */ public class CreateUserAbility extends LibreAbility { private Checkbox showNameCheckBox; @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.Ability_create_user); super.setUIContent(ResourceTable.Layout_ability_create_user); showNameCheckBox = (Checkbox)findComponentById(ResourceTable.Id_showNameCheckBox); @@ -57,12 +57,10 @@ public class CreateUserAbility extends LibreAbility { startOpenAbility(CreateUserAbility.this,HelpAbility.class.getName()); } }); - - Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); showNameCheckBox.setButtonElement(stateElement); } @@ -87,11 +85,7 @@ public class CreateUserAbility extends LibreAbility { config.website = text.getText().toString().trim(); text = (TextField) findComponentById(ResourceTable.Id_bioText); config.bio = text.getText().toString().trim(); - config.showName = showNameCheckBox.isChecked(); - - HttpCreateUserAction action = new HttpCreateUserAction(getContext(),this, config); -// action.execute(); } /** diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java index 3fe761758467de39c6a7641b848c68d56e6431c3..b52e03f4a478deba0cf5ded3ad9171352b93b077 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java @@ -45,16 +45,13 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen super.onStart(intent); // setContentView(R.layout.ability_help); super.setUIContent(ResourceTable.Layout_ability_help); - MainAbility.online = true; - this.instance = MainAbility.instance; - MainAbility.searching = false; - MainAbility.searchingPosts = false; + MainAbility.setOnline(true); + this.instance = MainAbility.getInstance(); + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); //switching to remote Connection. - MainAbility.connection = MainAbility.remoteConnection; - - MainAbility.instance = this.instance; - - + MainAbility.setConnection(MainAbility.getRemoteConnection()); + MainAbility.setInstance(instance); Button faqButton = (Button) findComponentById(ResourceTable.Id_faqButton); Button forumsButton = (Button) findComponentById(ResourceTable.Id_forumsButton); Button helpBotButton = (Button) findComponentById(ResourceTable.Id_helpBotButton); @@ -73,37 +70,25 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen ForumConfig instance = new ForumConfig(); instance.domain = ""; instance.name = "FAQ"; - - HttpResultAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void forums() { BrowseConfig config = new BrowseConfig(); config.domain = ""; config.type = "Forum"; - config.contentRating = MainAbility.contentRating; - - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); + config.contentRating = MainAbility.getContentRating(); } public void liveSupport() { ChannelConfig instance = new ChannelConfig(); instance.domain = ""; instance.name = "Help"; - - HttpFetchAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void helpBot() { InstanceConfig instance = new InstanceConfig(); instance.domain = ""; instance.name = "Help Bot"; - - HttpFetchAction action = new HttpFetchAction(this, instance, true); -// action.execute(); } public void website() { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java index 33a4ee3074e9c89fa4f42ef1d7ad0ef8cc1c4637..8be9620572852480f6e3f95eb8e1bc93ed0a8764 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java @@ -41,8 +41,8 @@ import ohos.agp.components.ListContainer; import ohos.agp.components.Text; import ohos.data.preferences.Preferences; -public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { - public static boolean offlineTemplate = false; +public class ListTemplateView extends LibreAbility { + private static boolean offlineTemplate = false; List items; final static String listOfBots[] = {"Empty", "Basic", "Personal Assistance"}; final static int imagesId[] = {ResourceTable.Media_bot, ResourceTable.Media_bot, ResourceTable.Media_bot}; @@ -52,14 +52,8 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { ListAdapter adapter; private ListContainer llview; - // Intent data = new Intent(); -// String temp; Text txt; - // @Override -// public String getType() { -// return "Bot"; -// } @SuppressWarnings("unchecked") @Override public void onStart(Intent intent) { @@ -85,16 +79,19 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { templates.setTitle(items.get(arg2).getTitle()); templates.setDec(items.get(arg2).getDec()); templates.setImageId(items.get(arg2).getImageId()); + MainAbility.setLaunchInstanceName(templates.getTitle()); + MainAbility.setLaunchInstanceId(templates.getId()); //saving a template number for getting the icons and pictures of the bot - saveAllData(MainAbility.launchInstanceName = templates.getTitle(), MainAbility.launchInstanceId = templates.getId(), MainAbility.templateID = arg2); - config.id = MainAbility.launchInstanceId; - config.name = MainAbility.launchInstanceName; + MainAbility.setTemplateID(arg2); + saveAllData(MainAbility.getLaunchInstanceName(), MainAbility.getLaunchInstanceId(), arg2); + config.id = MainAbility.getLaunchInstanceId(); + config.name = MainAbility.getLaunchInstanceName(); AvatarSelection.saveSelectedAvatar(templates.getTitle()); MainAbility.readZipAvatars(ListTemplateView.this, templates.getTitle()); - MainAbility.offlineSelectedImage = templates.getImageId(); - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - cookies.putString("botName", MainAbility.launchInstanceName); - cookies.putString("botID", MainAbility.launchInstanceId); + MainAbility.setOfflineSelectedImage(templates.getImageId()); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + cookies.putString("botName", MainAbility.getLaunchInstanceName()); + cookies.putString("botID", MainAbility.getLaunchInstanceId()); cookies.flushSync(); runWork(new Runnable() { @Override @@ -105,7 +102,7 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { runUI(new Runnable() { @Override public void run() { - if(MainAbility.launchInstanceName.contains("Assistance")){ + if(MainAbility.getLaunchInstanceName().contains("Assistance")){ startOpenAbility(ListTemplateView.this, ChatAbility2.class.getName()); }else{ startOpenAbility(ListTemplateView.this, ChatAbility.class.getName()); @@ -117,30 +114,15 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { }); } }); - offlineTemplate = false; + setOfflineTemplate(false); return; } - -// adapter = new ImageListAdapter(this, R.layout.image_list, (List) MainAbility.getAllTemplates(this)); -// llview.setAdapter(adapter); -// -// llview.setOnItemClickListener(new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { -// InstanceConfig templates = (InstanceConfig) (llview.getItemAtPosition(arg2)); -// Toast.makeText(ListTemplateView.this, templates.name + " Selected", Toast.LENGTH_SHORT).show(); -// data.putExtra("template", templates.name); -// setResult(RESULT_OK,data); -// finish(); -// } -// }); - HttpAction action = new HttpGetTemplatesAction(this); action.execute(); } public void saveAllData(String instanceId, String instanceName, int id) { - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); cookies.putString("instanceID", instanceId); cookies.putString("instanceName", instanceName); cookies.putInt("tempId", id); @@ -156,7 +138,7 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { return items; } - public class ListAdapter extends BaseItemProvider { + static class ListAdapter extends BaseItemProvider { private final Ability mActivity; private final LayoutScatter mInflater; @@ -204,7 +186,7 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { return component; } - private class ViewHolder { + private static class ViewHolder { Text title; Image icon; Text dec; @@ -218,4 +200,13 @@ public class ListTemplateView extends /*CreateWebMediumAbility*/LibreAbility { } } + public static boolean isOfflineTemplate() { + return offlineTemplate; + } + + + + public static void setOfflineTemplate(boolean offlineTemplate) { + ListTemplateView.offlineTemplate = offlineTemplate; + } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java index 4b92cafe10fd7743ff631fcdb55de3ec1d562d5e..fed73ed10507304e0eacffba5b56a66b1da89cbe 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java @@ -55,13 +55,17 @@ import java.util.List; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; - +/** + * Ability for creating a new user. + * + * @since 2021-04-16 + */ public class MicConfigAbility extends LibreAbility implements AsrListener { //Name - used for Log.d(classname, "") private final String CLASSNAME = "MicConfiguration"; - public boolean active; + private boolean active; private boolean isRecording; private double lastReply = System.currentTimeMillis(); private Button nextButton; @@ -88,7 +92,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { private DirectionalLayout spinOptions; private Text textOption; - public static final int REQ_PERMISSION_CODE = 1003; + private static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( Arrays.asList( @@ -118,8 +122,8 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { spinOptions = (DirectionalLayout) findComponentById(ResourceTable.Id_spinOptions); textOption = (Text) findComponentById(ResourceTable.Id_textOption); - ckOfflineSpeech.setChecked(MainAbility.offlineSpeech); - ckDebug.setChecked(ChatAbility.DEBUG); + ckOfflineSpeech.setChecked(MainAbility.isOfflineSpeech()); + ckDebug.setChecked(ChatAbility.isDEBUG()); //disabling buttons for recording sound playButton.setEnabled(false); @@ -141,7 +145,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { cookies.flushSync(); return; } - MainAbility.offlineSpeech = false; + MainAbility.setOfflineSpeech(false); cookies.putBoolean("offlineSpeech", false); cookies.flushSync(); }); @@ -149,13 +153,13 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { ckDebug.setCheckedStateChangedListener((absButton, b) -> { Preferences cookies = PreferencesUtils.getPreferences(this); if (b) { - ChatAbility.DEBUG = true; + ChatAbility.setDEBUG(true); cookies.putBoolean("debug", true); cookies.flushSync(); return; } //else - ChatAbility.DEBUG = false; + ChatAbility.setDEBUG(false); cookies.putBoolean("debug", false); cookies.flushSync(); }); @@ -202,17 +206,17 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { }); nextButton.setClickedListener(component -> { if (textOption.getText().equals("Hands Free")) { - MainAbility.handsFreeSpeech = true; - MainAbility.listenInBackground = true; + MainAbility.setHandsFreeSpeech(true); + MainAbility.setListenInBackground(true); Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); - cookies.putBoolean("listenInBackground", MainAbility.listenInBackground); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); + cookies.putBoolean("listenInBackground", MainAbility.isListenInBackground()); cookies.flushSync(); } else if (textOption.getText().equals("Google")) { - MainAbility.handsFreeSpeech = false; + MainAbility.setHandsFreeSpeech(false); Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); cookies.flushSync(); } if (nextButton.getText().equals("Select")) { @@ -257,7 +261,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { } - public void typeList() { + private void typeList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_select_list, null, false); @@ -353,7 +357,6 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { /** * IpPlayerCallback * - * @author VoiceRipple * @since 2021-04-29 */ public static class IpPlayerCallback implements Player.IPlayerCallback { @@ -427,7 +430,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { } if (volume != 0) { LogUtils.e("ChatActivity", "The volume changed and saved to : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -440,7 +443,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { super.onBackPressed(); } - public boolean deleteRecordedFile(String outputFile) { + private boolean deleteRecordedFile(String outputFile) { boolean deleted = false; File file = new File(outputFile); if (file.exists()) { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java index e116182a62d837c446d1da56b49f6bcc61471cf6..41d7ff83562f53454d1c37353570731af6095bef 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java @@ -24,7 +24,6 @@ import ohos.agp.components.Checkbox; import ohos.agp.components.Component; import ohos.agp.components.ComponentState; import ohos.agp.components.DirectionalLayout; -import ohos.agp.components.Image; import ohos.agp.components.LayoutScatter; import ohos.agp.components.RadioButton; import ohos.agp.components.Text; @@ -38,26 +37,23 @@ import ohos.agp.window.service.DisplayManager; import ohos.data.preferences.Preferences; import org.botlibre.sdk.MainAbility; import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpGetInstancesAction; import org.botlibre.sdk.ability.dialog.SearchDialogBuilder; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.util.PreferencesUtils; -import org.botlibre.sdk.util.ResUtil; +import org.botlibre.sdk.util.ResUtils; import java.util.Optional; /** * Search Ability for searching instances. + * + * @since 2021-04-16 */ public abstract class SearchAbility extends LibreAbility implements SelectListener { final static int TAGTEXT = 3,CATTEXT = 4; - private TextField tagsText,categoriesText; - private Image btnTag, btnCat; - private Text sortSpin,restrictSpin; - private boolean sortSpinOption = true; private int type = 0; private RadioButton publicRadio; private RadioButton radio; @@ -94,24 +90,18 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.ability_search); super.setUIContent(ResourceTable.Layout_ability_search); - - btnCat = (Image)findComponentById(ResourceTable.Id_btnCat); - btnTag = (Image)findComponentById(ResourceTable.Id_btnTag); - tagsText = (TextField) findComponentById(ResourceTable.Id_tagsText); - categoriesText = (TextField)findComponentById(ResourceTable.Id_categoriesText); browseButton = (Button) findComponentById(ResourceTable.Id_browseButton); menuButton = (Button) findComponentById(ResourceTable.Id_menuButton); Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); checkbox.setButtonElement(stateElement); - checkbox.setChecked(MainAbility.showImages); + checkbox.setChecked(MainAbility.isShowImages()); publicRadio = (RadioButton) findComponentById(ResourceTable.Id_publicRadio); publicRadio.setChecked(true); @@ -163,7 +153,7 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen @Override public void onClick(Component component) { type = 2; - SearchDialogBuilder.with(SearchAbility.this,MainAbility.contentRatings).setSelectInterface(SearchAbility.this); + SearchDialogBuilder.with(SearchAbility.this,MainAbility.getContentRatings()).setSelectInterface(SearchAbility.this); } }); @@ -180,80 +170,26 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen menu(); } }); - -// btnTag.setOnClickListener(new View.OnClickListener() { -// -// @Override -// public void onClick(View v) { -// Intent i = new Intent(SearchAbility.this,ListTagsView.class); -// i.putExtra("type", getType()); -// startAbilityForResult(i,TAGTEXT); -// } -// }); -// btnCat.setOnClickListener(new View.OnClickListener() { -// -// @Override -// public void onClick(View v) { -// Intent i = new Intent(SearchAbility.this,ListCategoriesView.class); -// i.putExtra("type", getType()); -// startAbilityForResult(i,CATTEXT); -// } -// }); - -// HttpAction action = new HttpGetTagsAction(this, getType()); -// action.execute(); -// -// action = new HttpGetCategoriesAction(this, getType()); -// action.execute(); -// MainAbility.searching = !MainAbility.browsing; } -// @Override -// protected void onResume() { -// if(sortSpinOption){ -// sortSpin.setSelection(3); -// sortSpinOption = false; -// } -// super.onResume(); -// } - - //Getting Info from the Opened Activities @Override protected void onAbilityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onAbilityResult(requestCode, resultCode, data); switch(requestCode){ case TAGTEXT: -// if(resultCode == RESULT_OK){ -// tagsText.setText(tagsText.getText()+data.getStringParam("tag") + ", "); //as Tags -// } break; case CATTEXT: -// if(resultCode == RESULT_OK){ -// categoriesText.setText(categoriesText.getText()+data.getStringParam("cat") + ", ");//as Categories -// } break; } } -// public void onDestroy() { -// super.onDestroy(); -// MainAbility.searching = false; -// } - public void browse() { -// Spinner sortSpin = (Spinner)findComponentById(ResourceTable.Id_sortSpin); -// config.sort = (String)sortSpin.getSelectedItem(); -// Spinner restrictSpin = (Spinner)findComponentById(ResourceTable.Id_restrictSpin); -// config.restrict = (String)restrictSpin.getSelectedItem(); -// //added contentRating -// Spinner contentRating = (Spinner) findComponentById(ResourceTable.Id_ContentRatingSpin); -// MainAbility.contentRating = (String) contentRating.getSelectedItem(); -// config.contentRating = MainAbility.contentRating; - //save contentRating - Preferences editor = PreferencesUtils.getPreferences(MainAbility.current); - editor.putString("contentRating", MainAbility.contentRating); + + private void browse() { + Preferences editor = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + editor.putString("contentRating", MainAbility.getContentRating()); editor.flushSync(); TextField tagText = (TextField)findComponentById(ResourceTable.Id_tagsText); @@ -263,19 +199,15 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen TextField filterEdit = (TextField)findComponentById(ResourceTable.Id_filterText); config.filter = filterEdit.getText().toString(); Checkbox checkbox = (Checkbox)findComponentById(ResourceTable.Id_imagesCheckBox); - MainAbility.showImages = checkbox.isChecked(); - + MainAbility.setShowImages(checkbox.isChecked()); config.type = getType(); - - HttpGetInstancesAction action = new HttpGetInstancesAction(SearchAbility.this, config, MainAbility.browsing); -// action.execute(); } - public StateElement setSelect() { + private StateElement setSelect() { StateElement stateElement = new StateElement(); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); return stateElement; } @@ -291,10 +223,10 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen } } }; - + public abstract String getType(); - public void menu() { + private void menu() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); DisplayAttributes displayAttributes = display.get().getAttributes(); @@ -312,8 +244,6 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen mybots.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { -// browseMyBots(); -// menuDialog.destroy(); } }); @@ -336,25 +266,14 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen }); } - public void browseMyBots() { - BrowseConfig config = new BrowseConfig(); - config.type = getType(); - config.typeFilter = "Personal"; - config.contentRating = "Mature"; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config, MainAbility.browsing); -// action.execute(); - } - - public void browseFeatured() { + private void browseFeatured() { BrowseConfig config = new BrowseConfig(); config.type = getType(); config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config, MainAbility.browsing); -// action.execute(); + config.contentRating = MainAbility.getContentRating(); } - public void browseCategories() { + private void browseCategories() { } @Override diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java deleted file mode 100644 index 07ab9d620cf25e2d854134a7a68e484704c519c4..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateAction.java +++ /dev/null @@ -1,82 +0,0 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -package org.botlibre.sdk.ability.actions; - -import org.botlibre.sdk.MainAbility; -import org.botlibre.sdk.config.WebMediumConfig; -import org.botlibre.sdk.util.PreferencesUtils; -import ohos.aafwk.ability.Ability; -import ohos.data.preferences.Preferences; - -public class HttpCreateAction extends HttpUIAction { - - WebMediumConfig config; - boolean finish; - - public HttpCreateAction(Ability ability, WebMediumConfig config) { - super(ability); - this.config = config; - this.finish = true; - } - - public HttpCreateAction(Ability ability, WebMediumConfig config, boolean finish) { - super(ability); - this.config = config; - this.finish = finish; - } - - @Override - protected String doInBackground(Void... params) { - try { - this.config = MainAbility.connection.create(this.config); - } catch (Exception exception) { - this.exception = exception; - } - return ""; - } - - @SuppressWarnings("rawtypes") - @Override - public void onPostExecute(String xml) { - super.onPostExecute(xml); - if (this.exception != null) { - return; - } - try { - MainAbility.instance = this.config; - - if (this.finish) { - this.ability.terminateAbility(); - } - - Preferences cookies= PreferencesUtils.getPreferences(this.ability); - cookies.putString(this.config.getType(), this.config.name); - cookies.flushSync(); - -// Class childAbility = MainAbility.getAbility(this.config); -// startOpenAbility(this.ability,childAbility.getName()); - - } catch (Exception error) { - this.exception = error; - MainAbility.error(this.exception.getMessage(), this.exception, this.ability); - return; - } - } - -} \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java index 18ff0673a175067bbddea811b127bb7fe77e792a..780d55257d687d948ae2becdaed4ac6562a400fc 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java @@ -27,19 +27,17 @@ import ohos.app.Context; public class HttpCreateUserAction extends HttpUIResultAction { UserConfig config; - private Context context; - public HttpCreateUserAction(Context context, Ability ability, UserConfig config) { + public HttpCreateUserAction(Ability ability, UserConfig config) { super(ability); this.config = config; - this.context = context; doInBackground(); } // @Override protected void doInBackground() { try { - this.config = MainAbility.connection.create(ability,this.config); + this.config = MainAbility.getConnection().create(ability,this.config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -50,7 +48,7 @@ public class HttpCreateUserAction extends HttpUIResultAction { return; } try { - MainAbility.user = this.config; + MainAbility.setUser(config); this.ability.terminateAbility(); } catch (Exception error) { this.exception = error; @@ -60,8 +58,7 @@ public class HttpCreateUserAction extends HttpUIResultAction { } -// @Override + public void onPostExecute(String xml) { -// super.onPostExecute(xml); } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java index d0e27b9e029e0249592174751b19031cbe9352f1..7b14d268a7a7401cc99ae22199ff5027db9401ff 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchAction.java @@ -29,6 +29,8 @@ import org.botlibre.sdk.config.InstanceConfig; import org.botlibre.sdk.config.WebMediumConfig; import org.botlibre.sdk.util.PreferencesUtils; +import static org.botlibre.sdk.MainAbility.*; + public class HttpFetchAction extends HttpUIResultAction { WebMediumConfig config; boolean launch; @@ -48,7 +50,7 @@ public class HttpFetchAction extends HttpUIResultAction { public void doInBackground(){ loadingDialog(); try { - this.config = MainAbility.connection.fetch(this.config); + this.config = getConnection().fetch(this.config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -79,33 +81,33 @@ public class HttpFetchAction extends HttpUIResultAction { return; } try { - MainAbility.instance = this.config; + setInstance(config); Preferences cookies= PreferencesUtils.getPreferences(this.ability); cookies.putString(this.config.getType(), this.config.name); cookies.flushSync(); - Class childAbility = MainAbility.getActivity(this.config); + Class childAbility = getActivity(this.config); if (this.launch && !this.config.isExternal) { if (this.config instanceof ChannelConfig) { // childAbility = LiveChatAbility.class; } else if (this.config instanceof InstanceConfig) { // childAbility = ChatAbility.class; } else if (this.config instanceof DomainConfig) { - MainAbility.connection.setDomain((DomainConfig)this.config); - MainAbility.domain = (DomainConfig)this.config; - MainAbility.tags = null; - MainAbility.categories = null; - MainAbility.forumTags = null; - MainAbility.forumCategories = null; - MainAbility.channelTags = null; - MainAbility.channelCategories = null; - MainAbility.domainTags=null; - MainAbility.domainCategories=null; - MainAbility.graphicTags = null; - MainAbility.graphicCategories = null; + getConnection().setDomain((DomainConfig)this.config); + setDomain((DomainConfig)this.config); + setTags(null); + setCategories(null); + setForumTags(null); + setForumCategories(null); + setChannelTags(null); + setChannelCategories(null); + setDomainTags(null); + setDomainCategories(null); + setGraphicTags(null); + setGraphicCategories(null); - MainAbility.type = MainAbility.defaultType; + setType(getDefaultType()); startOpenAbility(this.ability,MainAbility.class.getName()); return; @@ -114,11 +116,8 @@ public class HttpFetchAction extends HttpUIResultAction { config.typeFilter = "Public"; config.type = "Post"; - config.instance = MainAbility.instance.id; + config.instance = getInstance().id; config.sort = "date"; - - HttpGetPostsAction action = new HttpGetPostsAction(this.ability, config); -// action.execute(); return; } } else { @@ -128,7 +127,7 @@ public class HttpFetchAction extends HttpUIResultAction { startOpenAbility(this.ability,childAbility.getName()); } catch (Exception error) { this.exception = error; - MainAbility.error(this.exception.getMessage(), this.exception, this.ability); + error(this.exception.getMessage(), this.exception, this.ability); return; } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java index 6222aeb7081223e23c9b016988fd98557e0e34ea..dc18ddc5c3156581afc80e66a37b087e0bec9654 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFlagUserAction.java @@ -32,7 +32,7 @@ public class HttpFlagUserAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - MainAbility.connection.flag(this.config); + MainAbility.getConnection().flag(this.config); } catch (Exception exception) { this.exception = exception; } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetAvatarMediaAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetAvatarMediaAction.java index 9e2aff1ba6938c2632039624bd30bdbd13535388..42ea5ac37af0d014cfefd4cbbddb3ab109cc42a6 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetAvatarMediaAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetAvatarMediaAction.java @@ -39,7 +39,7 @@ public class HttpGetAvatarMediaAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.instances = MainAbility.connection.getAvatarMedia(config); + this.instances = MainAbility.getConnection().getAvatarMedia(config); } catch (Exception exception) { this.exception = exception; } @@ -52,7 +52,7 @@ public class HttpGetAvatarMediaAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.avatarMedias = this.instances; + MainAbility.setAvatarMedias(instances); if (this.finish) { this.ability.terminateAbility(); } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java index d9eb94280adbd2a4b22908c51895ae16ff014009..8866e8ea92b971e0b8922065e8f0b0af7608f700 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java @@ -27,112 +27,31 @@ import java.util.List; public class HttpGetInstancesAction extends HttpUIResultAction { - BrowseConfig config; - List instances; boolean finish = false; - boolean CustomAvatar = false; public HttpGetInstancesAction(Ability ability, BrowseConfig config) { super(ability); - this.config = config; doInBackground(); } public HttpGetInstancesAction(Ability ability, BrowseConfig config, boolean finish) { super(ability); - this.config = config; this.finish = finish; doInBackground(); } - public HttpGetInstancesAction(Ability ability, BrowseConfig config, boolean finish, boolean CustomAvatar) { - super(ability); - this.config = config; - this.finish = finish; - this.CustomAvatar = CustomAvatar; - } - public void doInBackground(){ loadingDialog(); - try { - this.instances = MainAbility.connection.browse(ability,config); - } catch (Exception exception) { - this.exception = exception; - removeDialog(); - return; - } onPostExecute(); } -// @Override -// protected String doInBackground(Void... params) { -// -// return ""; -// } - -// @Override public void onPostExecute() { -// super.onPostExecute(xml); if (this.exception != null) { return; } - MainAbility.instances = this.instances; if (this.finish) { this.ability.terminateAbility(); } -// Intent intent = null; -// MainAbility.browse = this.config; -// if (config.type.equals("Forum")) { -// intent = getIntent(this.ability, BrowseForumAbility.class.getName()); -// } else if (config.type.equals("Channel")) { -// intent = getIntent(this.ability, BrowseChannelAbility.class.getName()); -// } else if (config.type.equals("Domain")) { -// intent = getIntent(this.ability, BrowseDomainAbility.class.getName()); -// } else if (config.type.equals("Avatar")) { -// intent = getIntent(this.ability, BrowseAvatarAbility.class.getName()); -// } else if (config.type.equals("Graphic")) { -// intent = getIntent(this.ability, BrowseGraphicAbility.class.getName()); -// if (this.CustomAvatar) { -// //only happens when CustomAvatar is called -// intent.setParam("dataName", "Custom Avatar"); -// intent.setParam("dataCustomAvatar", true); -// } else { -// intent.setParam("dataCustomAvatar", false); -// } -// -// } else if (config.type.equals("Script")) { -// if (MainAbility.importingBotScript) { -// List onlyScripts = new ArrayList(); -// -// for (int i = 0; i < MainAbility.instances.size(); i++) { -// ScriptConfig config = (ScriptConfig) MainAbility.instances.get(i); -// if (config.categories.contains("Self") || config.categories.contains("AIML")) { -// onlyScripts.add(config); -// } -// } -// MainAbility.instances = onlyScripts; -// } else if (MainAbility.importingBotLog) { -// List onlyScripts = new ArrayList(); -// -// for (int i = 0; i < MainAbility.instances.size(); i++) { -// ScriptConfig config = (ScriptConfig) MainAbility.instances.get(i); -// if (config.categories.contains("Log") || config.categories.contains("AIML") || config.categories.contains("Response")) { -// onlyScripts.add(config); -// } -// } -// MainAbility.instances = onlyScripts; -// } -// intent = getIntent(this.ability, BrowseScriptAbility.class.getName()); -// } else { -// intent = getIntent(this.ability, BrowseAbility.class.getName()); -// } -// -// //for result only happens when RequestAbility calls it. -// if (this.CustomAvatar) { -// this.ability.startAbilityForResult(intent, 1); -// } else { -// this.ability.startAbility(intent); -// } } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetLearningAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetLearningAction.java index 40e01a437282e334daf74a2f3f02e0b1d7225302..584fc19cfc2c5b2d4c8c4580482c23abc89fe223 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetLearningAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetLearningAction.java @@ -35,7 +35,7 @@ public class HttpGetLearningAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.learning = MainAbility.connection.getLearning(this.config); + this.learning = MainAbility.getConnection().getLearning(this.config); } catch (Exception exception) { this.exception = exception; } @@ -49,7 +49,7 @@ public class HttpGetLearningAction extends HttpUIAction { return; } try { - MainAbility.learning = this.learning; + MainAbility.setLearning(learning); // ((LearningAbility)this.ability).resetView(); } catch (Exception error) { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java deleted file mode 100644 index 09f2164cca848c27379a0ee2fcad425fd34291e4..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetPostsAction.java +++ /dev/null @@ -1,77 +0,0 @@ -/****************************************************************************** - * - * Copyright 2014 Paphus Solutions Inc. - * - * Licensed under the Eclipse Public License, Version 1.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.eclipse.org/legal/epl-v10.html - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -package org.botlibre.sdk.ability.actions; - -import java.util.List; - - -import org.botlibre.sdk.MainAbility; -import org.botlibre.sdk.config.BrowseConfig; -import org.botlibre.sdk.config.ForumPostConfig; -import ohos.aafwk.ability.Ability; -import ohos.aafwk.content.Intent; - -public class HttpGetPostsAction extends HttpUIAction { - BrowseConfig config; - List posts; - boolean finish = false; - - public HttpGetPostsAction(Ability Ability, BrowseConfig config) { - super(Ability); - this.config = config; - } - - public HttpGetPostsAction(Ability Ability, BrowseConfig config, boolean finish) { - super(Ability); - this.config = config; - this.finish = finish; - } - - @Override - protected String doInBackground(Void... params) { - try { - this.posts = MainAbility.connection.getPosts(this.config); - } catch (Exception exception) { - this.exception = exception; - } - return ""; - } - - @Override - public void onPostExecute(String xml) { - super.onPostExecute(xml); - if (this.exception != null) { - return; - } - MainAbility.posts = this.posts; - - if (this.finish) { - this.ability.terminateAbility(); - } - MainAbility.browsePosts = this.config; - Intent intent = new Intent(); -// Operation operation = new Intent.OperationBuilder() -// .withDeviceId("") -// .withBundleName(this.ability.getBundleName()) -// .withAbilityName(BrowsePostAbility.class.getName()) -// .build(); -// intent.setOperation(operation); - this.ability.startAbility(intent); - } -} \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java index cf41f9c81aefcfb292699e84e16057d6138f270b..b6be9cf7f7783155eaa4ea845a1a0bcd6997f265 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java @@ -27,8 +27,7 @@ import javax.swing.text.html.ListView; import java.util.List; public class HttpGetTemplatesAction extends HttpAction { - ListView llview; - List templates; + public HttpGetTemplatesAction(Ability Ability) { super(Ability); @@ -37,20 +36,6 @@ public class HttpGetTemplatesAction extends HttpAction { @Override protected String doInBackground(Void... params) { - try { - this.templates = MainAbility.connection.getTemplates(); - } catch (Exception exception) { - this.exception = exception; - } return ""; } - - public void postExecute(String xml) { - if (this.exception != null) { - return; - } - - MainAbility.templates = this.templates; - - } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/CommandAdapter.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/CommandAdapter.java index 5220844068684f8f28760fb46ecf3de7ff6f0a36..3ec3b8120df01f8e14a9e7a744eedf817c5d3e13 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/CommandAdapter.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/CommandAdapter.java @@ -29,7 +29,6 @@ import java.util.List; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class CommandAdapter extends BaseItemProvider { @@ -93,9 +92,8 @@ public class CommandAdapter extends BaseItemProvider { * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; if (component == null) { component = mInflater.parse(ResourceTable.Layout_command_item, componentContainer, false); holder = new ViewHolder(component); @@ -115,7 +113,6 @@ public class CommandAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/EmoteAdapter.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/EmoteAdapter.java index b73f21ae2a337f4bab77739657562e47c3297abb..e68e4a5bc9ce9896a9686e59ed2b092162adb93a 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/EmoteAdapter.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/EmoteAdapter.java @@ -31,7 +31,6 @@ import java.util.Locale; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class EmoteAdapter extends BaseItemProvider { @@ -95,9 +94,9 @@ public class EmoteAdapter extends BaseItemProvider { * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; + if (component == null) { component = mInflater.parse(ResourceTable.Layout_emote_item, componentContainer, false); holder = new ViewHolder(component); @@ -146,7 +145,6 @@ public class EmoteAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java index 6b6e5f7a5b4508551fdbe969d3169da9981da5e5..22fd3458483934fb99390bbff63d582c61a5f528 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java @@ -26,7 +26,6 @@ import ohos.agp.components.Text; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerAdapter extends BaseItemProvider { @@ -42,7 +41,7 @@ public class SpinnerAdapter extends BaseItemProvider { */ public SpinnerAdapter(Ability ability, String[] types) { mAbility = ability; - this.types = types; + this.types = types.clone(); mInflater = LayoutScatter.getInstance(ability); } @@ -90,9 +89,8 @@ public class SpinnerAdapter extends BaseItemProvider { * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; if (component == null) { component = mInflater.parse(ResourceTable.Layout_simple_spinner_dropdown_item, componentContainer, false); @@ -109,7 +107,6 @@ public class SpinnerAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java index a75ead36800635748095bc8f89239222aa9e7517..89f91d097cfe268c52dd02ebb1ea335763a9c482 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java @@ -42,7 +42,6 @@ public class AvatarSelection extends Ability { final int [] imges = {}; final String [] names = {}; ((Text) findComponentById(ResourceTable.Id_theTitle)).setText("Select Avatar"); - final ListContainer listView = (ListContainer) findComponentById(ResourceTable.Id_theListView); ArrayList items = new ArrayList(); for (int i = 0; i < names.length; i++) { items.add(new OfflineTemplateConfig(imges[i],names[i],null,null)); @@ -51,8 +50,8 @@ public class AvatarSelection extends Ability { } public static void saveSelectedAvatar(String nameOfAvatar) { - MainAbility.nameOfAvatar = nameOfAvatar; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); + MainAbility.setNameOfAvatar(nameOfAvatar); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); cookies.putString("nameOfAvatar", nameOfAvatar); cookies.flushSync(); } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java index b14752da2ad09c11c8ac78699949724ab1af4531..53b2e35a54946f4423d193ec29a3f80f3502c7e1 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 语言对话框 * - * @author BotLibre * @since 2021-05-10 */ public class LanguageDialogBuilder { @@ -75,13 +74,13 @@ public class LanguageDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.languages); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getLanguages()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer list, Component component, int ii, long ll) { - MainAbility.selectInfo = MainAbility.languages[ii]; // 赋值 选择的选项 - selectListener.selectLanguageItem(MainAbility.languages[ii] + ""); + MainAbility.setSelectInfo(MainAbility.getLanguages()[ii]); // 赋值 选择的选项 + selectListener.selectLanguageItem(MainAbility.getLanguages()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java index 34c67053c103c3e2a87c24dca243287ed1c7ee15..2a575710711b1ba6da83d91e8c2c3447e9ad8d2d 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java @@ -35,7 +35,6 @@ import java.util.Optional; /** * 搜索对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SearchDialogBuilder { @@ -51,7 +50,7 @@ public class SearchDialogBuilder { * @param spinStr spinStr */ public SearchDialogBuilder(Ability context,String[] spinStr) { - this.spinStr = spinStr; + this.spinStr = spinStr.clone(); initLayout(context); } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java index d8caef1fa97f65a4d41c50e0c281907e74135f3d..30962a3c1db6da45daa68f8bbc8e25cbcddd8582 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerDialogBuilder { @@ -75,13 +74,13 @@ public class SpinnerDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.types); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getTypes()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer listCon, Component component, int ii, long ll) { - MainAbility.type = MainAbility.types[ii]; // 赋值 选择的选项 - selectListener.selectItem(MainAbility.types[ii] + ""); + MainAbility.setType(MainAbility.getTypes()[ii]); // 赋值 选择的选项 + selectListener.selectItem(MainAbility.getTypes()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java index 1c0419f9a72e8569c22923923a87c3b55b740012..7be2f536b9e4ca8d02ba737f6582b928029accf4 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java @@ -18,7 +18,7 @@ public class HttpChatWarAction extends HttpUIAction { protected String doInBackground(Void... params) { try { InstanceConfig instance = new InstanceConfig(); - this.instance = (InstanceConfig) MainAbility.connection.custom("chat-war", this.config, instance); + this.instance = (InstanceConfig) MainAbility.getConnection().custom("chat-war", this.config, instance); } catch (Exception exception) { this.exception = exception; } @@ -31,7 +31,7 @@ public class HttpChatWarAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.instance = this.instance; + MainAbility.setInstance(instance); } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java index b6be798ad96564bc3cf0c82b461dad5c727471ba..5864f9a11be7455c60a0675f1d52bff37ccc9e7c 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java @@ -41,154 +41,207 @@ import java.util.List; * Ability for user login. */ public class StartWarAbility extends LibreAbility implements Component.ClickedListener { - protected int browsing = 0; - public static InstanceConfig winner; - public static InstanceConfig looser; - public static InstanceConfig bot1; - public static InstanceConfig bot2; - public static String topic = "Hello"; - public boolean handsFreeSpeechWAS; - - private static long SECRET = 4357845875643L; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_start_war); - if(MainAbility.handsFreeSpeech) { - handsFreeSpeechWAS = true; - MainAbility.handsFreeSpeech = false; - } - - ((TextField)findComponentById(ResourceTable.Id_topicText)).setText(topic); - winner = null; - looser = null; - - if (bot1 == null) { - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - String last = cookies.getString("instance", null); - if (last != null && !last.isEmpty()) { - InstanceConfig config = new InstanceConfig(); - config.name = last; - } - } - - MainAbility.connection.setUser(MainAbility.user); - if (MainAbility.browsing) { - if ((MainAbility.instance instanceof InstanceConfig)) { - if (this.browsing == 0) { - bot1 = (InstanceConfig)MainAbility.instance; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - cookies.putString(bot1.getType(), bot1.name); - cookies.flushSync(); - } else { - bot2 = (InstanceConfig)MainAbility.instance; - } - } - } else if (winner != null) { - try{ - String text = "Last war " + winner.name + " beat " + looser.name + "."; - ((Text)findComponentById(ResourceTable.Id_winner)).setText(text); - ChatWarConfig config = new ChatWarConfig(); - config.winner = winner.id; - config.looser = looser.id; - config.topic = topic; - config.secret = String.valueOf(SECRET + MainAbility.user.user.length()); - HttpChatWarAction action = new HttpChatWarAction(this, config); - action.execute(); - }catch(Exception e){ - MainAbility.showMessage("You must be signed in to vote!", this); - } - } - MainAbility.browsing = false; - resetView(); - } - - public void resetView() { - try{ - List instances = new ArrayList(); - if (bot1 != null) { - instances.add(bot1); - } -// ListContainer list = (ListContainer) findComponentById(ResourceTable.Id_bot1List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); -// instances = new ArrayList(); -// if (bot2 != null) { -// instances.add(bot2); -// } -// list = (ListContainer) findComponentById(ResourceTable.Id_bot2List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); - }catch(Exception e){ - } - - Button warButton = (Button)findComponentById(ResourceTable.Id_warButton); - warButton.setClickedListener(this); - Button bot2Button = (Button)findComponentById(ResourceTable.Id_bot2Button); - bot2Button.setClickedListener(this); - Button bot1Button = (Button)findComponentById(ResourceTable.Id_bot1Button); - bot1Button.setClickedListener(this); - } - - /** - * Start a new war. - */ - public void war() { + protected int browsing = 0; + private static InstanceConfig winner; + private static InstanceConfig looser; + private static InstanceConfig bot1; + private static InstanceConfig bot2; + private String topic = "Hello"; + public boolean handsFreeSpeechWAS; + + private static long SECRET = 4357845875643L; + + @Override + public void onStart(Intent intent) { + super.onStart(intent); + super.setUIContent(ResourceTable.Layout_ability_start_war); + if (MainAbility.isHandsFreeSpeech()) { + handsFreeSpeechWAS = true; + MainAbility.setHandsFreeSpeech(false); + } + + ((TextField) findComponentById(ResourceTable.Id_topicText)).setText(topic); + setWinner(null); + setLooser(null); + if (bot1 == null) { + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + String last = cookies.getString("instance", null); + if (last != null && !last.isEmpty()) { + InstanceConfig config = new InstanceConfig(); + config.name = last; + } + } + + MainAbility.getConnection().setUser(MainAbility.getUser()); + if (MainAbility.isBrowsing()) { + if ((MainAbility.getInstance() instanceof InstanceConfig)) { + if (this.browsing == 0) { + setBot1((InstanceConfig)MainAbility.getInstance()); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + cookies.putString(bot1.getType(), bot1.name); + cookies.flushSync(); + } else { + setBot2((InstanceConfig) MainAbility.getInstance()); + } + } + } else if (winner != null) { + try { + String text = "Last war " + winner.name + " beat " + looser.name + "."; + ((Text) findComponentById(ResourceTable.Id_winner)).setText(text); + ChatWarConfig config = new ChatWarConfig(); + config.winner = winner.id; + config.looser = looser.id; + config.topic = topic; + config.secret = String.valueOf(SECRET + MainAbility.getUser().user.length()); + HttpChatWarAction action = new HttpChatWarAction(this, config); + action.execute(); + } catch (Exception e) { + MainAbility.showMessage("You must be signed in to vote!", this); + } + } + MainAbility.setBrowsing(false); + resetView(); + } + + public void resetView() { + try { + List instances = new ArrayList(); + if (bot1 != null) { + instances.add(bot1); + } + + } catch (Exception e) { + } + + Button warButton = (Button) findComponentById(ResourceTable.Id_warButton); + warButton.setClickedListener(this); + Button bot2Button = (Button) findComponentById(ResourceTable.Id_bot2Button); + bot2Button.setClickedListener(this); + Button bot1Button = (Button) findComponentById(ResourceTable.Id_bot1Button); + bot1Button.setClickedListener(this); + } + + /** + * Start a new war. + */ + public void war() { if (bot1 == null || bot2 == null) { - MainAbility.showMessage("Please select two bots to start a war", this); - return; + MainAbility.showMessage("Please select two bots to start a war", this); + return; } - topic = ((TextField)findComponentById(ResourceTable.Id_topicText)).getText().toString(); + topic = ((TextField) findComponentById(ResourceTable.Id_topicText)).getText().toString(); if (topic == null || topic.isEmpty()) { - MainAbility.showMessage("Please enter a topic", this); - return; + MainAbility.showMessage("Please enter a topic", this); + return; } - MainAbility.instance = bot1; - MainAbility.connection.setUser(null); + MainAbility.setInstance(bot1); + MainAbility.getConnection().setUser(null); // startOpenAbility(this,WarAbility.class.getName()); } - public void browseBot1() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - this.browsing = 0; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); - } - - public void browseBot2() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - MainAbility.instance = null; - this.browsing = 1; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); - } - - @Override - protected void onBackground() { - if(handsFreeSpeechWAS){ - MainAbility.handsFreeSpeech = true; - } - super.onBackground(); - } - - @Override - public void onClick(Component component) { - if(component.getId() == ResourceTable.Id_warButton){ - war(); - } - if(component.getId() == ResourceTable.Id_bot1Button){ - browseBot1(); - } - if(component.getId() == ResourceTable.Id_bot2Button){ - browseBot2(); - } - } + public void browseBot1() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(true); + this.browsing = 0; + } + + public void browseBot2() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(true); + MainAbility.setInstance(null); + this.browsing = 1; + } + + @Override + protected void onBackground() { + if (handsFreeSpeechWAS) { + MainAbility.setHandsFreeSpeech(true); + } + super.onBackground(); + } + + @Override + public void onClick(Component component) { + if (component.getId() == ResourceTable.Id_warButton) { + war(); + } + if (component.getId() == ResourceTable.Id_bot1Button) { + browseBot1(); + } + if (component.getId() == ResourceTable.Id_bot2Button) { + browseBot2(); + } + } + + /** + * getWinner + * + * @return InstanceConfig + */ + public static InstanceConfig getWinner() { + return winner; + } + + /** + * setWinner + * + * @param winner InstanceConfig + */ + public static void setWinner(InstanceConfig winner) { + StartWarAbility.winner = winner; + } + + + /** + * setLooser + * + * @param looser InstanceConfig + */ + public static void setLooser(InstanceConfig looser) { + StartWarAbility.looser = looser; + } + + /** + * getBot1 + * + * @return InstanceConfig + * */ + public static InstanceConfig getBot1() { + return bot1; + } + + /** + * setBot1 + * + * @param bot1 InstanceConfig + * */ + public static void setBot1(InstanceConfig bot1) { + StartWarAbility.bot1 = bot1; + } + + /** + * getBot2 + * + * @return InstanceConfig + * */ + public static InstanceConfig getBot2() { + return bot2; + } + + /** + * setBot2 + * + * @param bot2 InstanceConfig + * */ + public static void setBot2(InstanceConfig bot2) { + StartWarAbility.bot2 = bot2; + } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java index d37dd0797d08c1d2da7ea52d7fa1fb4058425d3c..8a1ac5e7523e6790480e21c42b3929e36fc9b0f8 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java @@ -31,7 +31,6 @@ import org.w3c.dom.Element; public class AvatarMedia extends Config { public String mediaId; public String name; - public String type; public String media; public String emotions; public String actions; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java index 992215f546b61796584a2dad19948c43847f057b..00b27ad42dc4233b1138230a5933b9b6e3916a6c 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java @@ -24,7 +24,6 @@ import java.io.StringWriter; * DTO for XML browse options. */ public class BrowseConfig extends Config { - public String type; public String typeFilter; public String category; public String tag; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ChannelConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ChannelConfig.java index 737feec8b50efe39961a2bf318902d4e36621ba9..becc5bc78955d2f086c902d4afcaefdfa1ac7cff 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ChannelConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ChannelConfig.java @@ -26,7 +26,6 @@ import org.w3c.dom.Element; * DTO for XML channel config. */ public class ChannelConfig extends WebMediumConfig { - public String type; public String videoAccessMode; public String audioAccessMode; public String messages; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ContentConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ContentConfig.java index 9d30d70e09b66ddb9ba0ecfd20b3cb2eca01f601..c9379f874672b09ed9a64d56cc734108f56e6f08 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ContentConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ContentConfig.java @@ -28,8 +28,7 @@ import org.w3c.dom.Node; * DTO for XML content config. */ public class ContentConfig extends Config { - - public String type; + public String name; public String icon; public String description; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java index 58a11bcdb65b62b99a6043e53e8ef2d1e1996719..b90cf07899883181f1126813a37fa9f75991360a 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java @@ -34,8 +34,7 @@ import org.w3c.dom.NodeList; public class ConversationConfig extends Config { public String id; public String creationDate; - public String type; - + public List input; public void parseXML(Element element) { @@ -55,13 +54,4 @@ public class ConversationConfig extends Config { } } - public String displayCreationDate() { - try { - SimpleDateFormat formater = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); - Date date = formater.parse(creationDate); - return ""; - } catch (Exception exception) { - return creationDate; - } - } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java index 283beaeb0d6742abe781061087bf8596b0e3d6e6..4578bfc2a0a0bc6ba0ace871fd198a4e25ecfa36 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java @@ -20,10 +20,7 @@ package org.botlibre.sdk.config; import java.io.StringWriter; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Locale; +import java.util.*; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -68,7 +65,12 @@ public class ForumPostConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, topic, summary, details, detailsText, forum, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isFeatured, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, replyCount, parent, avatar, replies); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); @@ -183,14 +185,4 @@ public class ForumPostConfig extends Config { config.id = this.id; return config; } - - public String displayCreationDate() { - try { - SimpleDateFormat formater = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); - Date date = formater.parse(creationDate); - return ""; - } catch (Exception exception) { - return creationDate; - } - } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java index a706bfb66db5664425fea2d3940d01fe3154768b..014f21dd000859d3ba1e03707161a5e73b821d6e 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java @@ -27,6 +27,7 @@ import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; /** @@ -65,7 +66,12 @@ public class IssueConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, title, priority, summary, details, detailsText, tracker, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isPriority, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, avatar); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java index 3237a0a40ffdeff201f2f67b22c0333050e02d21..d6bc1899f7df8a1a0988d9171d0098a92397c106 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java @@ -29,7 +29,6 @@ import org.w3c.dom.Element; public class MediaConfig extends Config { public long id; public String name; - public String type; public String file; public String key; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java index e0963e48207c8c00f6e5824e34d511d1bb8f2469..bf74806b009d1bb46c59b47e6fda23172871cfaf 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java @@ -19,6 +19,7 @@ package org.botlibre.sdk.config; import java.io.StringWriter; +import java.util.Objects; import ohos.utils.zson.ZSONException; import ohos.utils.zson.ZSONObject; @@ -73,6 +74,11 @@ public class ResponseConfig extends Config { return super.equals(object); } + @Override + public int hashCode() { + return Objects.hash(questionId, responseId, question, response, previous, onRepeat, label, topic, keywords, required, emotions, actions, poses, noRepeat, requirePrevious, requireTopic, flagged, correctness, command); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java index 8254fedb5fa75880d65d7c16fc1b25dd10107edc..21deb25795bb58bc6fa1c7ee40b1e5b2d79ade7c 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java @@ -23,6 +23,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.StringWriter; +import java.util.Objects; /** * DTO for XML user creation config. @@ -52,7 +53,6 @@ public class UserConfig extends Config { public String joined; public String lastConnect; - public String type; public boolean isFlagged; public String flaggedReason; @@ -75,6 +75,11 @@ public class UserConfig extends Config { return this.user != null && this.user.equals(((UserConfig)object).user); } + @Override + public int hashCode() { + return Objects.hash(password, newPassword, hint, name, showName, email, website, bio, over18, avatar, connects, bots, posts, messages, forums, scripts, graphics, avatars, domains, channels, joined, lastConnect, type, isFlagged, flaggedReason); + } + public void parseXML(Element element) { this.user = element.getAttribute("user"); this.name = element.getAttribute("name"); diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java index a9ccfff60ea54bf9cc0c0b994449abf51da5a5b1..60fffa0dcc8f666c173de215e5944ecdf30590af 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java @@ -62,9 +62,9 @@ import java.util.Map; public class MicroConnection extends SDKConnection implements TextListener { private WebMediumConfig config; protected Map activeBots = new HashMap(); - public static AvatarConfig avatarConfig; + public TextOutput message; - public static Bot bot; + private static Bot bot; /** * Create a micro/offline SDK connection. @@ -123,20 +123,6 @@ public class MicroConnection extends SDKConnection implements TextListener { } // this method will return a Bot with the default instance Bot bot = getBot(this.config.id); - try { - int i = 0; - while (i <= 4) { - if (bot == null) { - wait(1000); - bot = this.activeBots.get(config.instance); - } else if (bot != null) { - break; - } - i++; - } - } catch (Exception e) { - } - if (bot == null) { this.exception = new SDKException("Bot doesn't exists!"); throw this.exception; @@ -152,21 +138,8 @@ public class MicroConnection extends SDKConnection implements TextListener { TextInput textInput = new TextInput(config.message); textInput.setCorrection(config.correction); textInput.setOffended(config.offensive); - sense.input(textInput); ChatResponse response = new ChatResponse(); - if (this.message == null) { - //wait(5000); - } - if (this.message != null) { - response.message = this.message.getMessage(); - response.command = bot.avatar().getCommand(); - try { - avatarConfig.chatReply(response); - } catch (Exception e) { - } - } - return response; } @@ -179,9 +152,8 @@ public class MicroConnection extends SDKConnection implements TextListener { */ public T fetch(T config) { this.config = config; - MicroMemory.storageFileName = config.name; int id = Integer.parseInt(config.id); - bot = loadBot(config.name, id); + setBot(loadBot(config.name, id)); addBot(config.id, bot); if (!(config instanceof InstanceConfig)) { return super.fetch(config); @@ -210,7 +182,6 @@ public class MicroConnection extends SDKConnection implements TextListener { public void sendMessage(TextOutput message) { LogUtils.e("[MicroConnection]---->output-sendMessage", message.getMessage()); this.message = message; - notifyAll(); } /** @@ -311,4 +282,8 @@ public class MicroConnection extends SDKConnection implements TextListener { output.write(buffer, 0, bytesRead); } } + + public static void setBot(Bot bot) { + MicroConnection.bot = bot; + } } \ No newline at end of file diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java index 08e9fad0df263ba082fd99bdcda20e41e9887b3a..dbd8d90de392a5e1ed367359d25c53002101cd60 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java @@ -55,26 +55,10 @@ public class ChatListProvicer extends BaseItemProvider { if (message instanceof ChatConfig) { ChatConfig config = (ChatConfig) message; messageView.setText(config.message); - if (MainAbility.user != null && MainAbility.user.avatar != null) { -// if (MainAbility.online) { -// HttpGetImageAction.fetchImage(slice, MainAbility.user.avatar, userView); -// } else { -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, userView); -// } - } else { - //HttpGetImageAction.fetchImage(slice, SDKConnection.defaultUserImage(), userView); - } } else if (message instanceof ChatResponse) { ChatResponse config = (ChatResponse) message; - //messageView.setText(Utils.stripTags(config.message)); messageView.setText(config.message); userView.setPixelMap(ResourceTable.Media_bot); -// String avatar = ((ChatAbility) this.slice).getAvatarIcon(config); -// if (MainAbility.online) { -// HttpGetImageAction.fetchImage(slice, avatar, userView); -// } else { -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, userView); -// } } return cpt; diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java deleted file mode 100644 index 49fb24e5d366193acb5d67f0919bfa8d7e905647..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.botlibre.sdk.slice; - -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.util.LogUtils; -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.content.Intent; -import ohos.agp.window.dialog.CommonDialog; -import ohos.agp.window.dialog.IDialog; - -public class MainAbilitySlice extends AbilitySlice { - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_main); - } - - @Override - public void onActive() { - super.onActive(); - } - - @Override - public void onForeground(Intent intent) { - super.onForeground(intent); - } - - - public static void showMessage(String title, String message, AbilitySlice Ability) { - try { - CommonDialog dialog = new CommonDialog(Ability); - dialog.setContentText(message); - if (title != null) { - dialog.setTitleText(title); - } - dialog.setButton(CommonDialog.BUTTON1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - } - }); - dialog.show(); - } catch (Exception exception) { - LogUtils.e("showMessage", exception.toString()); - } - } - - public static void showMessage(String message, AbilitySlice Ability) { - showMessage(null, message, Ability); - } -} diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ApplicationJumpUtil.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ApplicationJumpUtil.java index 3e960477400524aac8a0991f6b361fa622babbbd..bb31a08e0c1904caa191d705181cfc36df9cd8da 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ApplicationJumpUtil.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ApplicationJumpUtil.java @@ -179,25 +179,28 @@ public class ApplicationJumpUtil { try { resolveinfoList = context.getBundleManager() .queryAbilityByIntent(resolveIntent, 0, 0); + + if(resolveinfoList != null && resolveinfoList.size()>0) { + String bundleName = null; + String className = null; + for (int ii = 0; ii < resolveinfoList.size(); ii++) { + String packge = resolveinfoList.get(ii).bundleName; + if (packge.equals(packageNa)) { + bundleName = resolveinfoList.get(ii).bundleName; + className = resolveinfoList.get(ii).className; + } + } + Intent mIntent = new Intent(); + Operation operation = new Intent.OperationBuilder() + .withAction("") + .withBundleName(bundleName) + .withAbilityName(className) + .build(); + mIntent.setOperation(operation); + context.startAbility(mIntent); + } } catch (RemoteException e) { e.getMessage(); } - String bundleName = null; - String className = null; - for (int ii = 0; ii < resolveinfoList.size(); ii++) { - String packge = resolveinfoList.get(ii).bundleName; - if (packge.equals(packageNa)) { - bundleName = resolveinfoList.get(ii).bundleName; - className = resolveinfoList.get(ii).className; - } - } - Intent mIntent = new Intent(); - Operation operation = new Intent.OperationBuilder() - .withAction("") - .withBundleName(bundleName) - .withAbilityName(className) - .build(); - mIntent.setOperation(operation); - context.startAbility(mIntent); } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java index 11de0c1dbb0959b87f241d5bcb198062a7f00948..1334dd65f46a0d053d5d88e53f6e799ba2e3f951 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java @@ -84,7 +84,7 @@ public abstract class AsyncTask { protected void done() { super.done(); try { - postResult(get()); + postResult(super.get()); } catch (InterruptedException | ExecutionException e) { e.getMessage(); } @@ -132,7 +132,6 @@ public abstract class AsyncTask { /** * 可以回调的一些函数 */ - @MainThread protected void onPreExecute() { } @@ -149,7 +148,6 @@ public abstract class AsyncTask { * * @param result */ - @MainThread protected void onPostExecute(Result result) { LogUtils.sop("onPostExecute"); } @@ -157,7 +155,6 @@ public abstract class AsyncTask { /** * onCancelled */ - @MainThread protected void onCancelled() { } @@ -166,7 +163,6 @@ public abstract class AsyncTask { * * @param progress */ - @MainThread protected void onProgressUpdate(Progress... progress) { } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java index 2038bcd9f3ab6f31ef3ed232145ee810afff36f1..63627c1e327c2fae500dff3b238b6e5d829fbc67 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java @@ -18,7 +18,6 @@ package org.botlibre.sdk.util; /** * 常量工具类 * - * @author: ColorPicker * @since 2021-04-16 */ public final class Constant { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/FileUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/FileUtils.java index 388fb0b0c9706de9ebbca02beaf31f59f7e04073..2543508cf6a0284b9833c361987e30e24f091bde 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/FileUtils.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/FileUtils.java @@ -9,7 +9,6 @@ import java.io.InputStream; /** * FileUtils * - * @author:username * @since 2021-06-10 */ public class FileUtils { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java index 9629cb0ba876eae2c207eba41ac2a4fb6a79441b..1ef2134a46013a0cd655657d0b6a06d492ce86fd 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java @@ -21,7 +21,6 @@ import ohos.hiviewdfx.HiLogLabel; /** * Log工具类 * - * @author:turnlayout * @since 2021-04-16 */ public final class LogUtils { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java deleted file mode 100644 index 22487dec32617bd1033c3ac26a49d2f9ebedf86a..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.CLASS; - -/** - * 注解 - * - * @author:turnlayout - * @since 2021-04-16 - */ -@Documented -@Retention(CLASS) -@Target({METHOD, CONSTRUCTOR, TYPE, PARAMETER}) -public @interface MainThread { -} diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java index d98fdc2b0dc053c102ce53400fabd58f5cb962d8..518720442318ce7324b8c6cd609785d91e9fcfb9 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java @@ -23,7 +23,6 @@ import ohos.data.preferences.Preferences; /** * PreferencesUtils * - * @author:username * @since 2021-05-10 */ public class PreferencesUtils { diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java deleted file mode 100644 index 01cbef0229d910b8d378736f00c67bee32cf80cd..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import ohos.agp.components.AttrSet; -import ohos.agp.components.element.Element; -import ohos.agp.components.element.ElementScatter; -import ohos.agp.components.element.PixelMapElement; -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.global.resource.RawFileEntry; -import ohos.global.resource.Resource; -import ohos.global.resource.ResourceManager; -import ohos.global.resource.WrongTypeException; -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; - -import java.io.IOException; -import java.util.Optional; - -/** - * ResUtil工具类 - * - * @author:turnlayout - * @since 2021-04-16 - */ -public class ResUtil { - private ResUtil() { - } - - /** - * get the path from id - * - * @param context the context - * @param id - * @return the path from id - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - return path; - } - return path; - } - - /** - * get the color - * - * @param context the context - * @param id - * @return the color - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get string - * - * @param context the context - * @param id - * @return string of the given id - */ - public static String getString(Context context, int id) { - String result = ""; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getString(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * getPreferences - * - * @param context - * @param id - * @param format - * @return str - */ - public static String getString(Context context, int id, Object... format) { - return String.format(getString(context, id), format); - } - - /** - * get the pixel map - * - * @param context the context - * @param id - * @return the pixel map - */ - public static Optional getPixelMap(Context context, int id) { - String path = getPathById(context, id); - if (path == null || path.length() <= 0) { - return Optional.empty(); - } - RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); - ImageSource.SourceOptions options = new ImageSource.SourceOptions(); - options.formatHint = "image/png"; - ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); - try { - Resource asset = assetManager.openRawFile(); - ImageSource source = ImageSource.create(asset, options); - return Optional.ofNullable(source.createPixelmap(decodingOptions)); - } catch (IOException e) { - return Optional.empty(); - } - } - - /** - * get the Pixel Map Element - * - * @param context the context - * @param resId - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * getElement - * - * @param context - * @param resId - * @return Element - */ - public static Element getElement(Context context, int resId) { - return ElementScatter.getInstance(context).parse(resId); - } - - /** - * getColorValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getColorValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getColorValue().getValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getDimensionValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getDimensionValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getIntValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getIntegerValue(); - if (value != 0) { - return value; - } - return defaultValue; - } -} - diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java index 07761b975827f0205af3568e5d2341f2d0e8348a..7308fdec9d01776a2adf1b6aa8b57299f7f2502e 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java @@ -15,43 +15,33 @@ package org.botlibre.sdk.util; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.element.Element; +import ohos.aafwk.ability.Ability; +import ohos.agp.components.Button; +import ohos.agp.components.Checkbox; +import ohos.agp.components.ComponentState; import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.components.element.VectorElement; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; -import ohos.agp.utils.Rect; +import ohos.agp.components.element.StateElement; import ohos.app.Context; import ohos.global.resource.NotExistException; import ohos.global.resource.RawFileEntry; import ohos.global.resource.Resource; import ohos.global.resource.ResourceManager; import ohos.global.resource.WrongTypeException; -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; -import ohos.media.image.common.PixelFormat; -import ohos.media.image.common.Size; +import org.botlibre.sdk.ResourceTable; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; /** * 资源工具类 * - * @author:hello * @since 2021-04-25 */ -public class ResUtils { +public final class ResUtils { private static final String TAG = "ResUtil"; - private static final int CONSTANT = 160; + private static final float CONSTANT = 160; private ResUtils() { } @@ -63,19 +53,8 @@ public class ResUtils { * @param vp vp * @return px */ - public static int vpToPx(Context context, float vp) { - return (int) (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp); - } - - /** - * px转vp - * - * @param context 上下文 - * @param px px - * @return vp - */ - public static int pxTovp(Context context, float px) { - return (int) (px / (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT)); + public static float vpToPx(Context context, float vp) { + return context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp; } /** @@ -84,139 +63,10 @@ public class ResUtils { * @param context 上下文 * @return 屏幕的宽,单位px */ - public static int getScreenWidth(Context context) { + public static float getScreenWidth(Context context) { return vpToPx(context, context.getResourceManager().getDeviceCapability().width); } - /** - * 获取屏幕的高 - * - * @param context 上下文 - * @return 屏幕的高,单位px - */ - public static int getScreenHeight(Context context) { - return vpToPx(context, context.getResourceManager().getDeviceCapability().height); - } - - /** - * 通过资源id获取路径 - * - * @param context 上下文 - * @param id 资源id - * @return 资源路径 - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - LogUtils.e("getPathById -> get null context"); - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getPathById -> get null ResourceManager"); - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - LogUtils.e("getPathById: " + e.getMessage()); - } - return path; - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static Color getNewColor(Context context, int id) { - return new Color(getColor(context, id)); - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - LogUtils.e("getColor -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getColor -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getColor: " + e.getMessage()); - } - return result; - } - - /** - * 通过资源id获取尺寸 - * - * @param context 上下文 - * @param id 资源Id - * @return 尺寸 - */ - public static float getDimen(Context context, int id) { - float result = 0; - if (context == null) { - LogUtils.e("getDimen -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getDimen: " + e.getMessage()); - } - return result; - } - - /** - * getBoolean - * - * @param context the context - * @param id the id - * @return get the boolean dimen value - */ - public static boolean getBoolean(Context context, int id) { - boolean result = false; - if (context == null) { - LogUtils.e("getBoolean -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException e) { - LogUtils.e("getBoolean -> IOException"); - } catch (NotExistException e) { - LogUtils.e("getBoolean -> NotExistException"); - } catch (WrongTypeException e) { - LogUtils.e("getBoolean -> WrongTypeException"); - } - return result; - } - /** * get string * @@ -226,143 +76,94 @@ public class ResUtils { */ public static String getString(Context context, int id) { String result = ""; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null context"); - return result; - } ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null ResourceManager"); - return result; - } try { result = manager.getElement(id).getString(); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> IOException"); + LogUtils.e("getString ->IOException"); } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> NotExistException"); + LogUtils.e("getString -> NotExistException"); } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> WrongTypeException"); + LogUtils.e("getString -> WrongTypeException"); } return result; } /** - * get the string array + * 每个单词第一个字母大写 * - * @param context the context - * @param id the string array id - * @return the string array + * @param str + * @return str */ - public static String[] getStringArray(Context context, int id) { - String[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getStringArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> WrongTypeException"); + public static String toUpperFirstCode(String str) { + String[] strs = str.split(" "); + StringBuilder sb = new StringBuilder(); + for (String strTmp : strs) { + char[] ch = strTmp.toCharArray(); + if (ch[0] >= 'a' && ch[0] <= 'z') { + ch[0] = (char) (ch[0] - 32); + } + String strT = new String(ch); + sb.append(strT).append(" "); } - return result; + return sb.toString().trim(); } /** - * get the int + * 设置button背景 * - * @param context the context - * @param id the int array - * @return the int array + * @param button + * @param resId */ - public static int getInt(Context context, int id) { - int result = 0; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null ResourceManager"); - return result; - } + public static void setBackground(Button button, int resId) { + Resource bgResource = null; + button.setBackground(null); try { - result = manager.getElement(id).getInteger(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> WrongTypeException"); + bgResource = button.getResourceManager().getResource(resId); + PixelMapElement pixBg = new PixelMapElement(bgResource); + button.setAroundElements(pixBg, null, null, null); + } catch (IOException | NotExistException e) { + e.getMessage(); } - return result; } /** - * get the int array + * 设置button背景 * - * @param context the context - * @param id the int array - * @return the int array + * @param ability + * @param checkbox */ - public static int[] getIntArray(Context context, int id) { - int[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> WrongTypeException"); - } - return result; + public static void setCheckboxBg(Ability ability, Checkbox checkbox) { + StateElement stateElement = new StateElement(); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_checked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_unchecked)); + checkbox.setButtonElement(stateElement); } /** - * get the vector drawable + * get the Pixel Map Element * * @param context the context - * @param id the drawable id - * @return the vector drawable + * @param resId + * @return the Pixel Map Element */ - public static VectorElement getVectorDrawable(Context context, int id) { - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getVectorDrawable -> get null context"); - return null; - } - return new VectorElement(context, id); + public static PixelMapElement getPixelMapDrawable(Context context, int resId) { + Optional optional = getPixelMap(context, resId); + return optional.map(PixelMapElement::new).orElse(null); } /** * get the pixel map * * @param context the context - * @param id the id + * @param id * @return the pixel map */ public static Optional getPixelMap(Context context, int id) { String path = getPathById(context, id); - if (path.isEmpty()) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> get empty path"); + if (path == null || path.length() <= 0) { return Optional.empty(); } RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); @@ -374,223 +175,31 @@ public class ResUtils { ImageSource source = ImageSource.create(asset, options); return Optional.ofNullable(source.createPixelmap(decodingOptions)); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> IOException"); + return Optional.empty(); } - return Optional.empty(); } /** - * get the Pixel Map Element + * get the path from id * * @param context the context - * @param resId the res id - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement - */ - public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle, - float sweepAngle) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } - - /** - * get the Element - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param rect the rect - * @return the Element - */ - public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.OVAL); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - element.setBounds(rect); - return element; - } - - /** - * get the Element - * - * @param inside the inside color - * @param rect the rect - * @return the Element - */ - public static Element getCustomRectGradientDrawable(Color inside, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.RECTANGLE); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setBounds(rect); - return element; - } - - /** - * 根据Resource获取背景(图片) - * - * @param resource 资源 - * @return 位图背景 - * @throws IOException - * @throws NotExistException - */ - public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException { - return new PixelMapElement(preparePixelmap(resource)); - } - - /** - * 根据Resource获取位图 - * - * @param resource 资源 - * @return 位图 - * @throws IOException - * @throws NotExistException - * @throws FileNotFoundException - */ - public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException { - ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions(); - ImageSource imageSource = null; - try { - imageSource = ImageSource.create(readResource(resource), srcOpts); - } finally { - close(resource); - } - if (imageSource == null) { - throw new FileNotFoundException(); - } - ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions(); - decodingOpts.desiredSize = new Size(0, 0); - decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0); - decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888; - - PixelMap pixelmap = imageSource.createPixelmap(decodingOpts); - return pixelmap; - } - - private static void close(Resource resource) { - if (resource != null) { - try { - resource.close(); - } catch (IOException e) { - Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage()); - } - } - } - - private static byte[] readResource(Resource resource) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bArr = new byte[1024]; - while (true) { - try { - int read = resource.read(bArr, 0, 1024); - if (read == -1) { - break; - } - byteArrayOutputStream.write(bArr, 0, read); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } finally { - try { - byteArrayOutputStream.close(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } - } - } - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource finish"); - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource len: " + byteArrayOutputStream.size()); - return byteArrayOutputStream.toByteArray(); - } - - /** - * rgb颜色值转换为rgba的ShapeElement - * - * @param rgbColor 颜色值 - * @return ShapeElement + * @param id + * @return the path from id */ - public static ShapeElement getShapeElement6(int rgbColor) { - if (rgbColor < 0 && rgbColor >= -0xffffff) { - rgbColor = rgbColor + 0xffffff + 1; + public static String getPathById(Context context, int id) { + String path = ""; + if (context == null) { + return path; } - if (rgbColor > 0 && rgbColor <= 0xffffff) { - rgbColor = alphaColor(rgbColor, 1.0f); + ResourceManager manager = context.getResourceManager(); + if (manager == null) { + return path; } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbColor)); - return shapeElement; - } - - /** - * rgb颜色值转换为rgba - * - * @param rgbColor 颜色值 - * @param alpha 透明度 - * @return int - */ - public static int alphaColor(int rgbColor, float alpha) { - if (rgbColor < 0) { - rgbColor = rgbColor + 0xffffff + 1; + try { + path = manager.getMediaPath(id); + } catch (IOException | NotExistException | WrongTypeException e) { + return path; } - int rgb = Math.max(0, rgbColor) << 8; - int al = (int) (alpha * 255); - return rgb + al; - } - - /** - * 颜色值rgba转换为ShapeElement - * - * @param rgbaColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement8(int rgbaColor) { - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbaColor)); - return shapeElement; + return path; } } diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java deleted file mode 100644 index 898266f217f2e0c75fb7528212784016618b8e60..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import org.botlibre.sdk.ResourceTable; -import ohos.aafwk.ability.Ability; -import ohos.agp.components.Button; -import ohos.agp.components.Checkbox; -import ohos.agp.components.ComponentState; -import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.StateElement; -import ohos.global.resource.NotExistException; -import ohos.global.resource.Resource; - -import java.io.IOException; - -/** - * ShapeUtils - * - * @author:username - * @since 2021-05-13 - */ -public class ShapeUtils { - private ShapeUtils() { - } - - /** - * 设置button背景 - * - * @param button - * @param resId - */ - public static void setBackground(Button button, int resId) { - Resource bgResource = null; - button.setBackground(null); - try { - bgResource = button.getResourceManager().getResource(resId); - PixelMapElement pixBg = new PixelMapElement(bgResource); - button.setAroundElements(pixBg, null, null, null); - } catch (IOException | NotExistException e) { - e.getMessage(); - } - } - - /** - * 设置button背景 - * - * @param ability - * @param checkbox - */ - public static void setCheckboxBg(Ability ability, Checkbox checkbox) { - StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_unchecked)); - checkbox.setButtonElement(stateElement); - } -} diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/StringUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/StringUtils.java deleted file mode 100644 index 00e160375459c3fd3348be0157f9130dbda37301..0000000000000000000000000000000000000000 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/StringUtils.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.botlibre.sdk.util; - -/** - * StringUtils - * - * @author:username - * @since 2021-06-15 - */ -public class StringUtils { - - /** - * 每个单词第一个字母大写 - * - * @param str - * @return str - */ - public static String toUpperFirstCode(String str) { - String[] strs = str.split(" "); - StringBuilder sb = new StringBuilder(); - for (String strTmp : strs) { - char[] ch = strTmp.toCharArray(); - if (ch[0] >= 'a' && ch[0] <= 'z') { - ch[0] = (char) (ch[0] - 32); - } - String strT = new String(ch); - sb.append(strT).append(" "); - } - return sb.toString().trim(); - } -} diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java index 1366f761cbfb6c5971f935cf8bad0c42da1831c9..92228166ddfbf1d6f1ebb33e2a6d24d20646572f 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java @@ -33,7 +33,7 @@ public class TextStream { public static final String HTTP =" \t\n\r\f\""; public static final String TOKENS =" \t\n\r\f.,:;!()?[]{}+=^&*\"`~|/\\<>"; public static final String TERMINATORS =".?!。"; - public static Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); + private static Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); public static Set IGNORABLE = new HashSet(Arrays.asList(new String[]{"'","`", "\"", ","})); /** diff --git a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java index 8a7995bd5c02b4c8de8136000b4cafe7970d9b2b..d95dd3595242a802e7397a6dec6ee6883d50b30f 100644 --- a/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java +++ b/BotLibreOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java @@ -27,7 +27,6 @@ import ohos.app.Context; /** * ToastUtils * - * @author:258767-shengyu * @since 2021-04-20 */ public class ToastUtils { diff --git a/PizzaBotOffline/build.gradle b/PizzaBotOffline/build.gradle index 67d49592dcd4742b75d4224a203792ed526f9919..a4bbee50c84428507c792bf978676f0ff6fe17a8 100644 --- a/PizzaBotOffline/build.gradle +++ b/PizzaBotOffline/build.gradle @@ -2,17 +2,6 @@ apply plugin: 'com.huawei.ohos.app' ohos { - signingConfigs { - debug { - storeFile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.p12') - storePassword '00000018FAA8E56771F402F726A8F9ECFCDBED9410306E156CD40D3412F2B82EC10270A42BF9E2D8' - keyAlias = 'debugKey' - keyPassword '00000018A082968AEC078212AB26B390BB301376468E26D511F7A32B95CB39EBD084DF7856F7A893' - signAlg = 'SHA256withECDSA' - profile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_sdk_890086000102149657.p7b') - certpath file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.cer') - } - } compileSdkVersion 6 defaultConfig { compatibleSdkVersion 5 diff --git a/PizzaBotOffline/entry/src/main/config.json b/PizzaBotOffline/entry/src/main/config.json index 2828ce9e7926dacdcd184cfa03e675f48c55dc3d..3f384f6ba09824156dabc3647eb3219f31740f50 100644 --- a/PizzaBotOffline/entry/src/main/config.json +++ b/PizzaBotOffline/entry/src/main/config.json @@ -95,24 +95,54 @@ "name": "ohos.permission.ACCESS_BIOMETRIC_INTERNAL" }, { + "name": "ohos.permission.READ_USER_STORAGE", "reason": "Read User Storage", - "name": "ohos.permission.READ_USER_STORAGE" + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Camera", - "name": "ohos.permission.READ_MEDIA" + "name": "ohos.permission.READ_MEDIA", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Media", - "name": "ohos.permission.MEDIA_LOCATION" + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.WRITE_USER_STORAGE", - "reason": "get WRITE_USER_STORAGE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.MICROPHONE", - "reason": "get MICROPHONE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } } ] } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java index a574ef952038d8ac6b41e80c36bd274694ec92fb..1910599e7ad360427e5d475a18c819d782eed9b2 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java @@ -18,18 +18,32 @@ package org.botlibre.sdk; /** * Credentials for use with hosted services on the BOT libre website, a free bot hosting service. * http://www.botlibre.com + * + * @since 2021-04-16 */ public class BOTlibreCredentials extends Credentials { - public static String DOMAIN = "www.botlibre.com"; - //public static String DOMAIN = "192.168.0.21:9080"; - public static String APP = ""; - //public static String APP = "/botlibre"; - public static String PATH = "/rest/api"; + /** + * DOMAIN + */ + public static final String DOMAIN = "www.botlibre.com"; + /** + * app + */ + public static final String APP = ""; + /** + * PATH + */ + public static final String PATH = "/rest/api"; - public BOTlibreCredentials(String applicationId) { - this.host = DOMAIN; - this.app = APP; - this.url = "https://" + DOMAIN + APP + PATH; - this.applicationId = applicationId; - } + /** + * BOTlibreCredentials + * + * @param applicationId + */ + public BOTlibreCredentials(String applicationId) { + this.host = DOMAIN; + this.app = APP; + this.url = "https://" + DOMAIN + APP + PATH; + this.applicationId = applicationId; + } } \ No newline at end of file diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java index 666bb6eec6bf7df3e066b1359ae83a5193778fc4..68f10af2fd5dd7734138478e73834ad898752fc3 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/MainAbility.java @@ -32,8 +32,6 @@ import ohos.agp.window.service.DisplayAttributes; import ohos.agp.window.service.DisplayManager; import ohos.app.Context; import ohos.data.preferences.Preferences; -import ohos.eventhandler.EventHandler; -import ohos.eventhandler.EventRunner; import ohos.media.audio.AudioManager; import ohos.media.audio.AudioRemoteException; import ohos.security.SystemPermission; @@ -61,7 +59,6 @@ import org.botlibre.sdk.config.InstanceConfig; import org.botlibre.sdk.config.IssueConfig; import org.botlibre.sdk.config.LearningConfig; import org.botlibre.sdk.config.OfflineTemplateConfig; -import org.botlibre.sdk.config.ResponseConfig; import org.botlibre.sdk.config.ScriptConfig; import org.botlibre.sdk.config.ScriptSourceConfig; import org.botlibre.sdk.config.UserConfig; @@ -101,30 +98,30 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * Enter your application ID here. * You can get an application ID from any of the services websites (Bot Libre, Bot Libre for Business) */ - public static String applicationId = "enter your application id here"; + private static String applicationId = "enter your application id here"; /** * Configure your connection credentials here. * Choose which service provider you wish to connect to. */ - public static SDKConnection connection, localConnection, remoteConnection; + private static SDKConnection connection, localConnection, remoteConnection; /** * To launch into a specific domain, enter the domain id here. */ - public static String domainId = null; + private static String domainId = null; /** * domain */ - public static DomainConfig domain; + private static DomainConfig domain; /** * domain */ - public static String defaultType = "Bots"; + private static String defaultType = "Bots"; /** * domain */ - public static boolean showAds = true; + private static boolean showAds = true; /** * Choose your service provider using the correct credentials. @@ -133,11 +130,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag localConnection = new MicroConnection(new BOTlibreCredentials(applicationId)); remoteConnection = new SDKConnection(new BOTlibreCredentials(applicationId)); connection = remoteConnection; - if (domainId != null) { - domain = new DomainConfig(); - domain.id = domainId; - connection.setDomain(domain); - } if (DEBUG) { showAds = false; connection.setDebug(true); @@ -147,20 +139,20 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag /** * If you are building a single instance app, then you can set the instance id or name here, */ - public static String launchInstanceId = ""; // i.e. "171" + private static String launchInstanceId = ""; // i.e. "171" /** * launchInstanceName */ - public static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" + private static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" /** * website */ - public static String website = "https://www.botlibre.com"; + private static String website = "https://www.botlibre.com"; /** * If you are building a single instance app, then you can set the launchType to */ - public static LaunchType launchType = LaunchType.Bot; + private static LaunchType launchType = LaunchType.Bot; @Override public void selectItem(String select) { @@ -177,165 +169,162 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * * @since 2021-04-16 */ - public enum LaunchType {Browse, Bot, Forum, Channel} + private enum LaunchType {Browse, Bot, Forum, Channel} /** * online */ - public static boolean online = true; + private static boolean online = true; /** * handsFreeSpeech */ - public static boolean handsFreeSpeech = true; + private static boolean handsFreeSpeech = true; /** * listenInBackground */ - public static boolean listenInBackground = false; + private static boolean listenInBackground = false; /** * micConfig */ - public static boolean micConfig = true; + private static boolean micConfig = true; /** * offlineSelectedImage */ - public static int offlineSelectedImage; + private static int offlineSelectedImage; /** * sound */ - public static boolean sound = true; + private static boolean sound = true; /** * disableVideo */ - public static boolean disableVideo; + private static boolean disableVideo; /** * webm */ - public static boolean webm = true; + private static boolean webm = true; /** * hd */ - public static boolean hd; + private static boolean hd; /** * deviceVoice */ - public static boolean deviceVoice; + private static boolean deviceVoice; /** * customVoice */ - public static boolean customVoice; + private static boolean customVoice; /** * translate */ - public static boolean translate; + private static boolean translate; /** * offlineSpeech */ - public static boolean offlineSpeech = false; + private static boolean offlineSpeech = false; /** * instance */ - public static WebMediumConfig instance; + private static WebMediumConfig instance; /** * post */ - public static ForumPostConfig post; + private static ForumPostConfig post; /** * issue */ - public static IssueConfig issue; + private static IssueConfig issue; /** * user */ - public static UserConfig user; + private static UserConfig user; /** * viewUser */ - public static UserConfig viewUser; + private static UserConfig viewUser; /** * type */ - public static String type = "Bots"; + private static String type = "Bots"; /** * voice */ - public static VoiceConfig voice = new VoiceConfig(); + private static VoiceConfig voice = new VoiceConfig(); /** * learning */ - public static LearningConfig learning = new LearningConfig(); + private static LearningConfig learning = new LearningConfig(); /** * script */ - public static ScriptSourceConfig script; + private static ScriptSourceConfig script; /** * conversation */ - public static String conversation; + private static String conversation; /** * template */ - public static String template = ""; + private static String template = ""; /** * tags */ - public static Object[] tags; + private static Object[] tags; /** * categories */ - public static Object[] categories; + private static Object[] categories; /** * channelTags */ - public static Object[] channelTags; + private static Object[] channelTags; /** * volume */ - public static int volume; + private static int volume; /** * contentRating */ - public static String contentRating; + private static String contentRating; /** * nameOfAvatar */ - public static String nameOfAvatar; + private static String nameOfAvatar; /** * instances */ - public static List instances = new ArrayList(); + private static List instances = new ArrayList(); /** * posts */ - public static List posts = new ArrayList(); + private static List posts = new ArrayList(); /** * current */ - public static MainAbility current; + private static MainAbility current; /** * browsing */ - public static boolean browsing; + private static boolean browsing; /** * searching */ - public static boolean searching; + private static boolean searching; /** * searchingPosts */ - public static boolean searchingPosts; - /** - * importingBotScript - */ - public static boolean importingBotScript = false; + private static boolean searchingPosts; + /** * importingBotLog */ - public static boolean importingBotLog = false; + private static boolean importingBotLog = false; /** * languages */ - public static String[] languages = new String[]{ + private static String[] languages = new String[]{ "Default", "af - Afrikaans", "sq - Albanian", "ar - Arabic", "hy - Armenian", "az - Azerbaijani", "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - Bulgarian", @@ -351,53 +340,53 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag /** * servers */ - public static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; + private static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; /** * servers */ - public static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; + private static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; Menu menu; /** * templateID */ - public static int templateID; + private static int templateID; /** * spin */ - public Button spin; + private Button spin; /** * createInstanceButton */ - public Button createInstanceButton; + private Button createInstanceButton; /** * browseButton */ - public Button browseButton; + private Button browseButton; /** * menuButton */ - public Button menuButton; + private Button menuButton; /** * loginButton */ - public Button loginButton; + private Button loginButton; /** * chatButton */ - public Button chatButton; + private Button chatButton; /** * logoutButton */ - public Button logoutButton; + private Button logoutButton; /** * viewUserButton */ - public Button viewUserButton; + private Button viewUserButton; /** * helpButton */ - public Button helpButton; + private Button helpButton; /** * reInitialize @@ -513,11 +502,10 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag @Override public void onStart(Intent intent) { super.onStart(intent); - searching = false; - browsing = false; - searchingPosts = false; - importingBotLog = false; - importingBotScript = false; + setSearching(false); + setBrowsing(false); + setSearchingPosts(false); + setImportingBotLog(false); if (user != null) { Preferences cookies = PreferencesUtils.getPreferences(this); cookies.putString("user", MainAbility.user.user); @@ -525,28 +513,18 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag cookies.flushSync(); } - - current = this; + setCurrent(this); Preferences cookies = PreferencesUtils.getPreferences(this); - // saved handsFreeSpeech toggle - load cookies. - handsFreeSpeech = cookies.getBoolean("handsfreespeech", handsFreeSpeech); - listenInBackground = cookies.getBoolean("listenInBackground", listenInBackground); - offlineSpeech = cookies.getBoolean("offlineSpeech", offlineSpeech); -// ChatAbility.DEBUG = cookies.getBoolean("debug", ChatAbility.DEBUG); //=============================================== - launchInstanceId = cookies.getString("instanceID", launchInstanceId); - launchInstanceName = cookies.getString("instanceName", launchInstanceName); - // saving the a number of array as an ID, for the sake of loading the - // exact saved bot. - templateID = cookies.getInt("tempId", templateID); - nameOfAvatar = cookies.getString("nameOfAvatar", nameOfAvatar); - System.out.println("Name of avatar: " + nameOfAvatar); - // load memory: by bot's name - + setHandsFreeSpeech(cookies.getBoolean("handsfreespeech", handsFreeSpeech)); + setListenInBackground(cookies.getBoolean("listenInBackground", listenInBackground)); + setOfflineSpeech(cookies.getBoolean("offlineSpeech", offlineSpeech)); + setLaunchInstanceId(cookies.getString("instanceID", launchInstanceId)); + setLaunchInstanceName(cookies.getString("instanceName", launchInstanceName)); + setTemplateID(cookies.getInt("tempId", templateID)); + setNameOfAvatar(cookies.getString("nameOfAvatar", nameOfAvatar)); loadMemoryByBot(); - // Checking and making sure that the mic is turned off to start - // configuring the microphone. - micConfig = cookies.getBoolean("miconfig", micConfig); + setMicConfig(cookies.getBoolean("miconfig", micConfig)); if (user == null) { String user = cookies.getString("user", null); @@ -578,20 +556,20 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag String nativeVoice = cookies.getString("nativeVoice", null); if (voice != null) { - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); + setCustomVoice(true); + setVoice( new VoiceConfig()); MainAbility.voice.voice = voice; MainAbility.voice.language = language; MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setDeviceVoice(MainAbility.voice.nativeVoice); } if (translate != null) { - MainAbility.translate = true; - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); + setTranslate(true); + setCustomVoice(true); + setVoice(new VoiceConfig()); MainAbility.voice.language = language; MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setDeviceVoice(MainAbility.voice.nativeVoice); } } @@ -607,8 +585,8 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } resetView(); - searching = false; - hd = isTablet(this); + setSearching(false); + setHd(isTablet(this)); } /** @@ -753,16 +731,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * showMessage */ public void loadMemoryByBot() { - MicroMemory.storageDir = getFilesDir(); - List items = new ArrayList(); - items = ListTemplateView.retriveTemplates(); + List items = ListTemplateView.retriveTemplates(); OfflineTemplateConfig oneItem; oneItem = items.get(templateID); System.out.println("StorageFileName :" + oneItem.getTitle()); - offlineSelectedImage = oneItem.getImageId(); - MicroMemory.storageFileName = oneItem.getTitle(); - launchInstanceName = oneItem.getTitle(); - launchInstanceId = oneItem.getId(); + setOfflineSelectedImage(oneItem.getImageId()); + setLaunchInstanceName(oneItem.getTitle()); + setLaunchInstanceId(oneItem.getId()); } /** @@ -788,9 +763,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag if (type.equals("Chat Bot Wars")) { return; } - if (type == null) { - type = MainAbility.defaultType; - } Button button = (Button) findComponentById(ResourceTable.Id_lastButton); if (button != null) { Preferences cookies = PreferencesUtils.getPreferences(this); @@ -904,19 +876,19 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag public void logout() { connection.disconnect(); - user = null; - instance = null; - conversation = null; - post = null; - posts = new ArrayList(); - instances = new ArrayList(); - domain = null; - tags = null; - categories = null; - learning = null; - voice = null; - customVoice = false; - translate = false; + setUser(null); + setInstance(null); + setConversation(null); + setPost(null); + setPosts(new ArrayList()); + setInstances(new ArrayList()); + setDomain(null); + setTags(null); + setCategories(null); + setLearning(null); + setVoice(null); + setCustomVoice(false); + setTranslate(false); Preferences editor = PreferencesUtils.getPreferences(this); editor.delete("user"); @@ -1041,7 +1013,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag * setOnline */ public void viewUser() { - viewUser = user; + setViewUser(user); } /** @@ -1081,7 +1053,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag type = MainAbility.defaultType; } if (type.equals("Bots")) { - MainAbility.template = ""; + setTemplate(""); } } @@ -1114,7 +1086,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } else if (type.equals("Avatars")) { config.type = "Avatar"; } else if (type.equals("Scripts")) { - importingBotScript = false; config.type = "Script"; } else if (type.equals("Graphics")) { config.type = "Graphic"; @@ -1135,21 +1106,17 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag config = new InstanceConfig(); OfflineTemplateConfig templates = new OfflineTemplateConfig(ResourceTable.Media_bot, "Pizza Bot", "", "" + 0, 0); //saving a template number for getting the icons and pictures of the bot - saveAllData(MainAbility.launchInstanceName = templates.getTitle(), MainAbility.launchInstanceId = templates.getId(), MainAbility.templateID = 0); + saveAllData(templates.getTitle(),templates.getId(), 0); config.id = MainAbility.launchInstanceId; config.name = MainAbility.launchInstanceName; AvatarSelection.saveSelectedAvatar(templates.getTitle()); //============================ - MainAbility.offlineSelectedImage = templates.getImageId(); + setOfflineSelectedImage(templates.getImageId()); startOpenAbility(this, ChatAbility.class.getName()); } else { config = new InstanceConfig(); config.name = MainAbility.launchInstanceName; config.id = MainAbility.launchInstanceId; } - } else if (MainAbility.launchType == LaunchType.Forum) { - config = new ForumConfig(); - } else if (MainAbility.launchType == LaunchType.Channel) { - config = new ChannelConfig(); } } @@ -1171,7 +1138,7 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag /** * selectInfo */ - public static String selectInfo = ""; + private static String selectInfo = ""; Text languageselect; /** @@ -1205,17 +1172,10 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag LanguageDialogBuilder.with(MainAbility.this).setSelectLanguageInterface(MainAbility.this); } }); - - int index = -1; - - if (MainAbility.voice != null && MainAbility.voice.language != null) { - index = Arrays.asList(MainAbility.languages).indexOf(MainAbility.voice.language); - } if (MainAbility.voice != null && MainAbility.voice.language != null) { for (int i = 0; i < spinnerAdapter.getCount(); i++) { if (MainAbility.languages[i].contains(MainAbility.voice.language + " - ")) { -// spin.setSelection(i); - selectInfo = MainAbility.languages[i]; + setSelectInfo(MainAbility.languages[i]); } } } @@ -1262,4 +1222,457 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } }); } + + + public static boolean isDEBUG() { + return DEBUG; + } + + public static boolean isADULT() { + return ADULT; + } + + public static String getApplicationId() { + return applicationId; + } + + public static void setApplicationId(String applicationId) { + MainAbility.applicationId = applicationId; + } + + public static SDKConnection getConnection() { + return connection; + } + + public static void setConnection(SDKConnection connection) { + MainAbility.connection = connection; + } + + public static SDKConnection getLocalConnection() { + return localConnection; + } + + public static void setLocalConnection(SDKConnection localConnection) { + MainAbility.localConnection = localConnection; + } + + public static SDKConnection getRemoteConnection() { + return remoteConnection; + } + + public static void setRemoteConnection(SDKConnection remoteConnection) { + MainAbility.remoteConnection = remoteConnection; + } + + public static String getDomainId() { + return domainId; + } + + public static void setDomainId(String domainId) { + MainAbility.domainId = domainId; + } + + public static DomainConfig getDomain() { + return domain; + } + + public static void setDomain(DomainConfig domain) { + MainAbility.domain = domain; + } + + public static String getDefaultType() { + return defaultType; + } + + public static void setDefaultType(String defaultType) { + MainAbility.defaultType = defaultType; + } + + public static boolean isShowAds() { + return showAds; + } + + public static void setShowAds(boolean showAds) { + MainAbility.showAds = showAds; + } + + public static String getLaunchInstanceId() { + return launchInstanceId; + } + + public static void setLaunchInstanceId(String launchInstanceId) { + MainAbility.launchInstanceId = launchInstanceId; + } + + public static String getLaunchInstanceName() { + return launchInstanceName; + } + + public static void setLaunchInstanceName(String launchInstanceName) { + MainAbility.launchInstanceName = launchInstanceName; + } + + public static String getWebsite() { + return website; + } + + public static void setWebsite(String website) { + MainAbility.website = website; + } + + public static LaunchType getLaunchType() { + return launchType; + } + + public static void setLaunchType(LaunchType launchType) { + MainAbility.launchType = launchType; + } + + public static boolean isOnline() { + return online; + } + + public static boolean isHandsFreeSpeech() { + return handsFreeSpeech; + } + + public static void setHandsFreeSpeech(boolean handsFreeSpeech) { + MainAbility.handsFreeSpeech = handsFreeSpeech; + } + + public static boolean isListenInBackground() { + return listenInBackground; + } + + public static void setListenInBackground(boolean listenInBackground) { + MainAbility.listenInBackground = listenInBackground; + } + + public static boolean isMicConfig() { + return micConfig; + } + + public static void setMicConfig(boolean micConfig) { + MainAbility.micConfig = micConfig; + } + + public static int getOfflineSelectedImage() { + return offlineSelectedImage; + } + + public static void setOfflineSelectedImage(int offlineSelectedImage) { + MainAbility.offlineSelectedImage = offlineSelectedImage; + } + + public static boolean isSound() { + return sound; + } + + public static void setSound(boolean sound) { + MainAbility.sound = sound; + } + + public static boolean isDisableVideo() { + return disableVideo; + } + + public static void setDisableVideo(boolean disableVideo) { + MainAbility.disableVideo = disableVideo; + } + + public static boolean isWebm() { + return webm; + } + + public static void setWebm(boolean webm) { + MainAbility.webm = webm; + } + + public static boolean isHd() { + return hd; + } + + public static void setHd(boolean hd) { + MainAbility.hd = hd; + } + + public static boolean isDeviceVoice() { + return deviceVoice; + } + + public static void setDeviceVoice(boolean deviceVoice) { + MainAbility.deviceVoice = deviceVoice; + } + + public static boolean isCustomVoice() { + return customVoice; + } + + public static void setCustomVoice(boolean customVoice) { + MainAbility.customVoice = customVoice; + } + + public static boolean isTranslate() { + return translate; + } + + public static void setTranslate(boolean translate) { + MainAbility.translate = translate; + } + + public static boolean isOfflineSpeech() { + return offlineSpeech; + } + + public static void setOfflineSpeech(boolean offlineSpeech) { + MainAbility.offlineSpeech = offlineSpeech; + } + + public static WebMediumConfig getInstance() { + return instance; + } + + public static void setInstance(WebMediumConfig instance) { + MainAbility.instance = instance; + } + + public static ForumPostConfig getPost() { + return post; + } + + public static void setPost(ForumPostConfig post) { + MainAbility.post = post; + } + + public static IssueConfig getIssue() { + return issue; + } + + public static void setIssue(IssueConfig issue) { + MainAbility.issue = issue; + } + + public static UserConfig getUser() { + return user; + } + + public static void setUser(UserConfig user) { + MainAbility.user = user; + } + + public static UserConfig getViewUser() { + return viewUser; + } + + public static void setViewUser(UserConfig viewUser) { + MainAbility.viewUser = viewUser; + } + + public static String getType() { + return type; + } + + public static void setType(String type) { + MainAbility.type = type; + } + + public static VoiceConfig getVoice() { + return voice; + } + + public static void setVoice(VoiceConfig voice) { + MainAbility.voice = voice; + } + + public static LearningConfig getLearning() { + return learning; + } + + public static void setLearning(LearningConfig learning) { + MainAbility.learning = learning; + } + + public static ScriptSourceConfig getScript() { + return script; + } + + public static void setScript(ScriptSourceConfig script) { + MainAbility.script = script; + } + + public static String getConversation() { + return conversation; + } + + public static void setConversation(String conversation) { + MainAbility.conversation = conversation; + } + + public static String getTemplate() { + return template; + } + + public static void setTemplate(String template) { + MainAbility.template = template; + } + + public static Object[] getTags() { + return tags.clone(); + } + + /** + * setTags + * @param tag + */ + public static void setTags(Object[] tag) { + if(tag!=null){ + tags = tag.clone(); + } + } + + public static Object[] getCategories() { + return categories.clone(); + } + + public static void setCategories(Object[] categorie) { + if(categorie!=null){ + categories = categorie.clone(); + } + } + + public static Object[] getChannelTags() { + return channelTags.clone(); + } + + public static void setChannelTags(Object[] channelTag) { + channelTags = channelTag.clone(); + } + + public static int getVolume() { + return volume; + } + + public static void setVolume(int volume) { + MainAbility.volume = volume; + } + + public static String getContentRating() { + return contentRating; + } + + public static void setContentRating(String contentRating) { + MainAbility.contentRating = contentRating; + } + + public static String getNameOfAvatar() { + return nameOfAvatar; + } + + public static void setNameOfAvatar(String nameOfAvatar) { + MainAbility.nameOfAvatar = nameOfAvatar; + } + + public static List getInstances() { + return instances; + } + + public static void setInstances(List instances) { + MainAbility.instances = instances; + } + + public static List getPosts() { + return posts; + } + + public static void setPosts(List posts) { + MainAbility.posts = posts; + } + + public static MainAbility getCurrent() { + return current; + } + + public static void setCurrent(MainAbility current) { + MainAbility.current = current; + } + + public static boolean isBrowsing() { + return browsing; + } + + public static void setBrowsing(boolean browsing) { + MainAbility.browsing = browsing; + } + + public static boolean isSearching() { + return searching; + } + + public static void setSearching(boolean searching) { + MainAbility.searching = searching; + } + + public static boolean isSearchingPosts() { + return searchingPosts; + } + + public static void setSearchingPosts(boolean searchingPosts) { + MainAbility.searchingPosts = searchingPosts; + } + + public static boolean isImportingBotLog() { + return importingBotLog; + } + + public static void setImportingBotLog(boolean importingBotLog) { + MainAbility.importingBotLog = importingBotLog; + } + + public static String[] getLanguages() { + return languages.clone(); + } + + public static void setLanguages(String[] language) { + languages = language.clone(); + } + + public static String[] getServers() { + return servers.clone(); + } + + public static void setServers(String[] server) { + servers = server.clone(); + } + + public static String[] getTypes() { + return types.clone(); + } + + public static void setTypes(String[] type) { + types = type.clone(); + } + + public static int getTemplateID() { + return templateID; + } + + public static void setTemplateID(int templateID) { + MainAbility.templateID = templateID; + } + + public static String getSelectInfo() { + return selectInfo; + } + + public static void setSelectInfo(String selectInfo) { + MainAbility.selectInfo = selectInfo; + } + + public Text getLanguageselect() { + return languageselect; + } + + public void setLanguageselect(Text languageselect) { + this.languageselect = languageselect; + } } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java index c27e8ba7f56f0d8dd7360095bcc201244c02d163..ecc039ee15c475479a54e56156940b2ab7015612 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/SDKConnection.java @@ -59,8 +59,8 @@ import java.util.List; * @since 2021-04-16 */ public class SDKConnection { - protected static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - protected static String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; + private static final String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; + private static final String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; protected String url; protected UserConfig user; @@ -101,10 +101,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-user", config.toXML()); Element root = parse(xml); - if (root == null) { - this.user = null; - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -149,9 +145,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POSTUpdate(ability, this.url + "/create-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -173,9 +166,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-forum-post", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ForumPostConfig post = new ForumPostConfig(); post.parseXML(root); @@ -196,9 +186,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-issue", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { IssueConfig issue = new IssueConfig(); issue.parseXML(root); @@ -222,9 +209,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -248,9 +232,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -335,9 +316,6 @@ public class SDKConnection { String xml = POST(this.url + "/get-default-responses", config.toXML()); List defaultResponses = new ArrayList(); Element root = parse(xml); - if (root == null) { - return defaultResponses; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { defaultResponses.add(((Element) root.getChildNodes().item(index)).getChildNodes().item(0).getTextContent()); } @@ -351,7 +329,7 @@ public class SDKConnection { * @return str */ public String[] getAccessModes() { - return accessModes; + return accessModes.clone(); } /** @@ -360,7 +338,7 @@ public class SDKConnection { * @return mediaAccessModes */ public String[] getMediaAccessModes() { - return mediaAccessModes; + return mediaAccessModes.clone(); } @@ -499,7 +477,6 @@ public class SDKConnection { System.out.println("POST: " + url); System.out.println("XML: " + xml); } - String result = ""; Response response = null; try { ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), @@ -520,7 +497,10 @@ public class SDKConnection { } this.exception = new SDKException(exception); } - return response.body().toString(); + if (response != null) { + return response.body().toString(); + } + return null; } /** diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java index 47bfcd33e18f1f92a9ce21261dd9a14a90c4b9f4..e2d9f0201872bb750e5b0017ac734b8528aff60c 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java @@ -15,7 +15,6 @@ package org.botlibre.sdk.ability; -import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Checkbox; @@ -30,9 +29,6 @@ import ohos.agp.components.webengine.JsCallback; import ohos.agp.components.webengine.WebView; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.PopupDialog; -import ohos.agp.window.service.Display; -import ohos.agp.window.service.DisplayAttributes; -import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.WindowManager; import ohos.ai.asr.AsrClient; import ohos.ai.asr.AsrIntent; @@ -70,14 +66,12 @@ import org.botlibre.sdk.provider.ChatListProvicer; import org.botlibre.sdk.util.LogUtils; import org.botlibre.sdk.util.PreferencesUtils; import org.botlibre.sdk.util.ResUtils; -import org.botlibre.sdk.util.ShapeUtils; import org.botlibre.sdk.util.ToastUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; -import java.util.Optional; import java.util.UUID; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; @@ -93,7 +87,6 @@ public class ChatAbility extends LibreAbility { /** * ability */ - private static Ability ability; private static final int ASR_RESULT = 9; private static final int BEGIN_SPEECH = 10; private static final int END_SPEECH = 11; @@ -103,7 +96,7 @@ public class ChatAbility extends LibreAbility { * videoLayout */ private Component videoLayout; - public Image bigImage; + private Image bigImage; private DirectionalLayout directionYes; private DirectionalLayout directionSelect; private DirectionalLayout directionType; @@ -134,7 +127,7 @@ public class ChatAbility extends LibreAbility { private long mLastUpTime; private long mLastDownTime; - public static boolean isListening; + private static boolean isListening; protected boolean ttsInit = false; /** @@ -149,14 +142,12 @@ public class ChatAbility extends LibreAbility { private int type; protected InstanceConfig instance; private int stateLayouts = 0; - public boolean music = false; - public static List messages = new ArrayList(); - public ChatResponse response; - public Player audioPlayer; - public String currentAudio; + private static List messages = new ArrayList(); + private ChatResponse response; + private Player audioPlayer; - public boolean videoError; + private boolean videoError; protected AvatarConfig avatar; protected String avatarId; protected boolean changingVoice; @@ -166,14 +157,14 @@ public class ChatAbility extends LibreAbility { protected PixelMap icon; //flag will check if the mic is ON or OFF - public static boolean micLastStat; + private static boolean micLastStat; private AudioCapturer mAudioCapturer; private boolean isFlag; private ChatListProvicer chatProvider; - public static final int REQ_PERMISSION_CODE = 1003; + private static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( Arrays.asList( @@ -301,7 +292,7 @@ public class ChatAbility extends LibreAbility { @Override public void onEvent(int eventType, PacMap pacMap) { if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) { - VoiceConfig voice = MainAbility.voice; + VoiceConfig voice = MainAbility.getVoice(); float pitch = 1; if (voice != null && voice.pitch != null && voice.pitch.length() > 0) { try { @@ -495,7 +486,6 @@ public class ChatAbility extends LibreAbility { protected void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_chat); - ability = this; //clear the messages from the listView - messages.clear(); @@ -503,16 +493,16 @@ public class ChatAbility extends LibreAbility { //setStreamVolume(); //Music Volume is Enabled. audioManager = new AudioManager(this); - if (MainAbility.sound) { + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } //For "scream" issue - micLastStat = MainAbility.listenInBackground; + micLastStat = MainAbility.isListenInBackground(); getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS); - this.instance = (InstanceConfig) MainAbility.instance; + this.instance = (InstanceConfig) MainAbility.getInstance(); tvTitle = ((Text) findComponentById(ResourceTable.Id_title)); imAvatar = (Image) findComponentById(ResourceTable.Id_icon); @@ -524,18 +514,6 @@ public class ChatAbility extends LibreAbility { ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); -// asrClient = AsrClient.createAsrClient(this).orElse(null); -// initIntent = new AsrIntent(); -// initIntent.setVadFrontWaitMs(2000); -// initIntent.setVadEndWaitMs(2000); -// initIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM); -// asrClient.init(initIntent, asrListener); - - //Last time will be saved for the MIC. -// if (MainAbility.listenInBackground && MainAbility.handsFreeSpeech) { -// microphoneThread(thread); -// } - //scrollVie added and stuff scrollView = (ListContainer) findComponentById(ResourceTable.Id_chatList); menuLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_menuMLayout); @@ -560,9 +538,9 @@ public class ChatAbility extends LibreAbility { buttonType = (Button) findComponentById(ResourceTable.Id_button_type); textInfo = (Text) findComponentById(ResourceTable.Id_textInfo); webView.load("http://www.baidu.com"); - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { setMicIcon(false, false); - } else if (!MainAbility.listenInBackground) { + } else if (!MainAbility.isListenInBackground()) { setMicIcon(false, false); } // resetVideoErrorListener(); @@ -597,7 +575,7 @@ public class ChatAbility extends LibreAbility { } }); - if (MainAbility.translate) { + if (MainAbility.isTranslate()) { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); } else { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); @@ -643,10 +621,10 @@ public class ChatAbility extends LibreAbility { }); micButton.setClickedListener(component -> { - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { reqPermissions(); } else { - ToastUtils.showCenterToast(ability, "Your device doesn't support Speech to Text"); + ToastUtils.showCenterToast(this, "Your device doesn't support Speech to Text"); } }); @@ -719,7 +697,7 @@ public class ChatAbility extends LibreAbility { } else if (mClickcount == 2) { mSecondClick = System.currentTimeMillis(); if (mSecondClick - mFirstClick < 1000) { - boolean isVideo = !MainAbility.disableVideo && !videoError && response != null + boolean isVideo = !MainAbility.isDisableVideo() && !videoError && response != null && response.isVideo(); videoLayout = findComponentById(ResourceTable.Id_videoLayout); if (bigImage.getVisibility() == Component.VISIBLE) { @@ -773,37 +751,22 @@ public class ChatAbility extends LibreAbility { avatarLayout.setVisibility(Component.VISIBLE); } }); - - if (!MainAbility.online) { -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, this.bigImage); -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, (Image) findComponentById(ResourceTable.Id_responseImageView)); -// HttpGetImageAction.setImage(MainAbility.offlineSelectedImage, findComponentById(ResourceTable.Id_icon)); - } else { - //HttpGetImageAction.fetchImage(this, this.instance.avatar, imAvatar); - //HttpGetImageAction.fetchImage(this, instance.avatar, this.bigImage); - //HttpGetImageAction.fetchImage(this, instance.avatar, (Image) findComponentById(ResourceTable.Id_responseImageView)); - } - final ChatConfig config = new ChatConfig(); //config.instance = instance.id; config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; + config.avatarHD = MainAbility.isHd(); + config.speak = !MainAbility.isDeviceVoice(); } - public void menuList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void menuList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_menu_chat, null, false); @@ -818,12 +781,12 @@ public class ChatAbility extends LibreAbility { Checkbox checkBox5 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox5); Checkbox checkBox6 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox6); Checkbox checkBox7 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox7); - checkBox1.setChecked(MainAbility.sound); - checkBox2.setChecked(MainAbility.deviceVoice); - checkBox3.setChecked(MainAbility.handsFreeSpeech); - checkBox5.setChecked(MainAbility.disableVideo || this.videoError); - checkBox6.setChecked(MainAbility.webm); - checkBox7.setChecked(MainAbility.hd); + checkBox1.setChecked(MainAbility.isSound()); + checkBox2.setChecked(MainAbility.isDeviceVoice()); + checkBox3.setChecked(MainAbility.isHandsFreeSpeech()); + checkBox5.setChecked(MainAbility.isDisableVideo() || this.videoError); + checkBox6.setChecked(MainAbility.isWebm()); + checkBox7.setChecked(MainAbility.isHd()); checkBox1.setClickable(false); checkBox2.setClickable(false); checkBox3.setClickable(false); @@ -849,10 +812,10 @@ public class ChatAbility extends LibreAbility { toggleDisableVideo(); break; case ResourceTable.Id_menuItem6: - MainAbility.webm = !MainAbility.webm; + MainAbility.setWebm(!MainAbility.isWebm()); break; case ResourceTable.Id_menuItem7: - MainAbility.hd = !MainAbility.hd; + MainAbility.setHd(!MainAbility.isHd()); break; } menuDialog.hide(); @@ -871,11 +834,7 @@ public class ChatAbility extends LibreAbility { menuDialog.show(); } - public void typeList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void typeList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_type_list, null, false); @@ -929,19 +888,19 @@ public class ChatAbility extends LibreAbility { return config; } - public void submitChat() { + private void submitChat() { ChatConfig config = new ChatConfig(); //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); //config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } //config.avatarHD = MainAbility.hd; @@ -959,7 +918,7 @@ public class ChatAbility extends LibreAbility { } mainHandler.sendEvent(AUTO_RESPONSE, 1000); //Check the volume - AudioManager audioManager = new AudioManager(ability); + AudioManager audioManager = new AudioManager(this); int volume = 0; try { volume = audioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC); @@ -971,12 +930,12 @@ public class ChatAbility extends LibreAbility { ToastUtils.showCenterToast(this, "Please check 'Media' volume"); volumeChecked = false; } - MainAbility.listenInBackground = false; + MainAbility.setListenInBackground(false); } - public void toggleSound() { - MainAbility.sound = !MainAbility.sound; - if (MainAbility.sound) { + private void toggleSound() { + MainAbility.setSound(!MainAbility.isSound()); + if (MainAbility.isSound()) { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 5); } else { audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); @@ -984,50 +943,45 @@ public class ChatAbility extends LibreAbility { resetToolbar(); } - public void toggleHandsFreeSpeech() { - MainAbility.handsFreeSpeech = !MainAbility.handsFreeSpeech; - if (!MainAbility.handsFreeSpeech) { + private void toggleHandsFreeSpeech() { + MainAbility.setHandsFreeSpeech(!MainAbility.isHandsFreeSpeech()); + if (!MainAbility.isHandsFreeSpeech()) { stopListening(); - } else if (MainAbility.handsFreeSpeech) { + } else if (MainAbility.isHandsFreeSpeech()) { beginListening(); } - Preferences cookies = PreferencesUtils.getPreferences(this.ability); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); + Preferences cookies = PreferencesUtils.getPreferences(this); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); cookies.flushSync(); } - public void toggleDisableVideo() { + private void toggleDisableVideo() { if (this.videoError) { this.videoError = false; - MainAbility.disableVideo = false; + MainAbility.setDisableVideo(false); } else { - MainAbility.disableVideo = !MainAbility.disableVideo; + MainAbility.setDisableVideo(!MainAbility.isDisableVideo()); } } - public void toggleDeviceVoice() { - MainAbility.deviceVoice = !MainAbility.deviceVoice; + private void toggleDeviceVoice() { + MainAbility.setDeviceVoice(!MainAbility.isDeviceVoice()); } - public void resetToolbar() { - if (MainAbility.sound) { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_sound); + private void resetToolbar() { + if (MainAbility.isSound()) { + ResUtils.setBackground(soundButton, ResourceTable.Media_sound); } else { - ShapeUtils.setBackground(soundButton, ResourceTable.Media_mute); + ResUtils.setBackground(soundButton, ResourceTable.Media_mute); } } @Override public void onActive() { - MainAbility.searching = false; - MainAbility.searchingPosts = false; - if (MainAbility.browsing && (MainAbility.instance instanceof AvatarConfig)) { - if (MainAbility.user == null || MainAbility.user.type == null || MainAbility.user.type.isEmpty() || MainAbility.user.type.equals("Basic")) { - //MainAbility.showMessage("You must upgrade to get access to this avatar", this); - //super.onResume(); - //return; - } - this.avatar = (AvatarConfig) MainAbility.instance; + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + if (MainAbility.isBrowsing() && (MainAbility.getInstance() instanceof AvatarConfig)) { + this.avatar = (AvatarConfig) MainAbility.getInstance(); this.avatarId = this.avatar.id; if (this.bigImage.getVisibility() == Component.HIDE) { this.bigImage.setVisibility(Component.VISIBLE); @@ -1036,21 +990,15 @@ public class ChatAbility extends LibreAbility { this.videoLayout.setVisibility(Component.HIDE); } } - MainAbility.browsing = false; - if ((MainAbility.instance instanceof InstanceConfig) && MainAbility.instance.id.equals(this.instance.id)) { - //this.instance = (InstanceConfig) MainAbility.instance; - } else { - //MainAbility.instance = this.instance; - } + MainAbility.setBrowsing(false); if (this.changingVoice) { this.changingVoice = false; - //resetTTS(); } resetTTS(); super.onActive(); } - public void resetTTS() { + private void resetTTS() { ttsClient.stopSpeak(); ttsClient.release(); ttsClient.destroy(); @@ -1064,18 +1012,8 @@ public class ChatAbility extends LibreAbility { } } - public String getAvatarIcon(ChatResponse config) { - if (this.avatar != null) { - return this.avatar.avatar; - } - if (config == null || config.isVideo()) { - //return this.instance.avatar; - } - return config.avatar; - } - - public void micConfiguration() { - Intent intent = getIntent(ability, MicConfigAbility.class.getName()); + private void micConfiguration() { + Intent intent = getIntent(this, MicConfigAbility.class.getName()); startAbility(intent); terminateAbility(); } @@ -1091,7 +1029,7 @@ public class ChatAbility extends LibreAbility { if (this.instance != null) { ChatConfig config = new ChatConfig(); //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; + config.conversation = MainAbility.getConversation(); config.disconnect = true; } @@ -1169,8 +1107,7 @@ public class ChatAbility extends LibreAbility { } private void restartListening() { - //debug("restartListening"); - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { return; } if (!isListening) { @@ -1190,7 +1127,7 @@ public class ChatAbility extends LibreAbility { } - public void debug(final String text) { + private void debug(final String text) { ChatResponse ready = new ChatResponse(); ready.message = text; messages.add(ready); @@ -1201,21 +1138,21 @@ public class ChatAbility extends LibreAbility { private void muteMicBeep(boolean mute) { - debug("muteMicBeep:" + mute + ":" + MainAbility.volume); - AudioManager audioManager = new AudioManager(ability); + debug("muteMicBeep:" + mute + ":" + MainAbility.getVolume()); + AudioManager audioManager = new AudioManager(this); if (mute) { LogUtils.sop("muteMicBeep : " + 0); //if its true then the Volume will be zero. audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } else { - LogUtils.sop("muteMicBeep : " + MainAbility.volume); + LogUtils.sop("muteMicBeep : " + MainAbility.getVolume()); //if its false, the Volume will put back on - audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.volume); + audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.getVolume()); } } private void setStreamVolume() { - AudioManager audioManager = new AudioManager(ability); + AudioManager audioManager = new AudioManager(this); int volume = 0; try { volume = audioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC); @@ -1225,7 +1162,7 @@ public class ChatAbility extends LibreAbility { if (volume != 0) { debug("setStreamVolume:" + volume); LogUtils.sop("setStreamVolume : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -1233,15 +1170,15 @@ public class ChatAbility extends LibreAbility { setStreamVolume(); //debug("beginListening:"); try { - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { return; } - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { muteMicBeep(true); isListening = true; } - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { muteMicBeep(false); return; } @@ -1257,12 +1194,12 @@ public class ChatAbility extends LibreAbility { setMicIcon(true, false); } catch (Exception exception) { LogUtils.sop("CatchError: " + exception.getMessage()); - ToastUtils.showCenterToast(ability, "Your device doesn't support Speech to Text"); + ToastUtils.showCenterToast(this, "Your device doesn't support Speech to Text"); } } - public void setAudio() { + private void setAudio() { AudioStreamInfo audioStreamInfo = new AudioStreamInfo.Builder() .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT) .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_IN_MONO) diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java index 184f900a194a49a2eb00c60a1b96e20a87e5b975..30200ec6d03f6221a595f0359231e09cc0fc9b52 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java @@ -23,8 +23,8 @@ import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; public class ListTemplateView extends /*CreateWebMediumAbility*/Ability { - public static boolean offlineTemplate = false; - List items; + // public static boolean offlineTemplate = false; + // List items; final static String listOfBots [] = {"Empty" , "Basic", "Personal Assistance"}; final static int imagesId [] = {ResourceTable.Media_bot, ResourceTable.Media_bot , ResourceTable.Media_bot}; final static String listOfDec [] = {"A completely empty template loaded with no knowledge or scripts.", diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java index bd3933af1174f46c98eeffd8b462c73126f285e9..54fd9dd3e8d6cf75931bb72d06eb62cccc6af54a 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/MicConfigAbility.java @@ -52,12 +52,16 @@ import java.util.List; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; - +/** + * MicConfigAbility + * + * @since 2021-04-25 + */ public class MicConfigAbility extends LibreAbility implements AsrListener { private final String CLASSNAME = "MicConfiguration"; - public boolean active; + private boolean active; private Button nextButton; private Text txt; private boolean failedOfflineLanguage = false; @@ -81,7 +85,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { private DirectionalLayout spinOptions; private Text textOption; - public static final int REQ_PERMISSION_CODE = 1003; + private static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( Arrays.asList( @@ -111,7 +115,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { spinOptions = (DirectionalLayout) findComponentById(ResourceTable.Id_spinOptions); textOption = (Text) findComponentById(ResourceTable.Id_textOption); - ckOfflineSpeech.setChecked(MainAbility.offlineSpeech); + ckOfflineSpeech.setChecked(MainAbility.isOfflineSpeech()); ckDebug.setChecked(false); //disabling buttons for recording sound @@ -134,7 +138,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { cookies.flushSync(); return; } - MainAbility.offlineSpeech = false; + MainAbility.setOfflineSpeech(false); cookies.putBoolean("offlineSpeech", false); cookies.flushSync(); }); @@ -179,17 +183,17 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { }); nextButton.setClickedListener(component -> { if (textOption.getText().equals("Hands Free")) { - MainAbility.handsFreeSpeech = true; - MainAbility.listenInBackground = true; + MainAbility.setHandsFreeSpeech(true); + MainAbility.setListenInBackground(true); Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); - cookies.putBoolean("listenInBackground", MainAbility.listenInBackground); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); + cookies.putBoolean("listenInBackground", MainAbility.isListenInBackground()); cookies.flushSync(); } else if (textOption.getText().equals("Google")) { - MainAbility.handsFreeSpeech = false; + MainAbility.setHandsFreeSpeech(false); Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); + cookies.putBoolean("handsfreespeech", MainAbility.isHandsFreeSpeech()); cookies.flushSync(); } if (nextButton.getText().equals("Select")) { @@ -234,7 +238,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { } - public void typeList() { + private void typeList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_select_list, null, false); @@ -330,7 +334,6 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { /** * IpPlayerCallback * - * @author VoiceRipple * @since 2021-04-29 */ public static class IpPlayerCallback implements Player.IPlayerCallback { @@ -404,7 +407,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { } if (volume != 0) { LogUtils.e("ChatAbility", "The volume changed and saved to : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -417,16 +420,7 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { super.onBackPressed(); } - public boolean deleteRecordedFile(String outputFile) { - boolean deleted = false; - File file = new File(outputFile); - if (file.exists()) { - deleted = file.delete(); - } - return deleted; - } - - public boolean deleteRecordedFile(File outputFile) { + private boolean deleteRecordedFile(File outputFile) { boolean deleted = false; if (outputFile.exists()) { deleted = outputFile.delete(); @@ -470,7 +464,6 @@ public class MicConfigAbility extends LibreAbility implements AsrListener { } - @Override public void onError(int error) { runUi(new Runnable() { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java index 951dd3fa42fe7a242a9671f5e4d4323c3683160e..887639d908c6c908523193f36d673c2c87fee011 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java @@ -45,7 +45,7 @@ public class HttpConnectAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { - this.config = MainAbility.connection.connect(config); + this.config = MainAbility.getConnection().connect(config); return ""; } @@ -55,7 +55,7 @@ public class HttpConnectAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.user = this.config; + MainAbility.setUser(this.config); if (this.ability instanceof MainAbility) { ((MainAbility) this.ability).resetView(); } @@ -63,8 +63,8 @@ public class HttpConnectAction extends HttpUIAction { if (this.finish) { Preferences cookies = PreferencesUtils.getPreferences(ability); - cookies.putString("user", MainAbility.user.user); - cookies.putString("token", MainAbility.user.token); + cookies.putString("user", MainAbility.getUser().user); + cookies.putString("token", MainAbility.getUser().token); cookies.flushSync(); this.ability.terminateAbility(); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java index 0d8dac226f0c4e85c637ef5a06fed54b64b8c5fa..c4b5aafce56e1528552d65ebc5d59171c53b0078 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java @@ -27,8 +27,6 @@ import ohos.app.Context; */ public class HttpCreateUserAction extends HttpUIAction { UserConfig config; - private Context context; - /** * HttpCreateUserAction * @@ -39,16 +37,16 @@ public class HttpCreateUserAction extends HttpUIAction { public HttpCreateUserAction(Context context, Ability ability, UserConfig config) { super(ability); this.config = config; - this.context = context; + // this.context = context; } @Override protected String doInBackground(Void... params) { - this.config = MainAbility.connection.create(ability, this.config); + this.config = MainAbility.getConnection().create(ability, this.config); if (this.exception != null) { return ""; } - MainAbility.user = this.config; + MainAbility.setUser(this.config); this.ability.terminateAbility(); return ""; } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java index 6b6e5f7a5b4508551fdbe969d3169da9981da5e5..d494f5a5c0d5691ed9b312035ecb31b737eae4ac 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java @@ -26,7 +26,6 @@ import ohos.agp.components.Text; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerAdapter extends BaseItemProvider { @@ -42,7 +41,7 @@ public class SpinnerAdapter extends BaseItemProvider { */ public SpinnerAdapter(Ability ability, String[] types) { mAbility = ability; - this.types = types; + this.types = types.clone(); mInflater = LayoutScatter.getInstance(ability); } @@ -85,14 +84,13 @@ public class SpinnerAdapter extends BaseItemProvider { * getComponent * * @param position position - * @param component1 component1 + * @param component component1 * @param componentContainer componentContainer * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; if (component == null) { component = mInflater.parse(ResourceTable.Layout_simple_spinner_dropdown_item, componentContainer, false); @@ -109,7 +107,6 @@ public class SpinnerAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java index 64bcfd24dbb3a4c9006e0de964875f1650ab191c..f2b6075487d02e7273b8aacf79f96da1545ab994 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java @@ -41,7 +41,6 @@ public class AvatarSelection extends Ability { final int[] imges = {}; final String[] names = {}; ((Text) findComponentById(ResourceTable.Id_theTitle)).setText("Select Avatar"); - final ListContainer listView = (ListContainer) findComponentById(ResourceTable.Id_theListView); ArrayList items = new ArrayList(); for (int ii = 0; ii < names.length; ii++) { items.add(new OfflineTemplateConfig(imges[ii], names[ii], null, null)); @@ -54,8 +53,8 @@ public class AvatarSelection extends Ability { * @param nameOfAvatar */ public static void saveSelectedAvatar(String nameOfAvatar) { - MainAbility.nameOfAvatar = nameOfAvatar; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); + MainAbility.setNameOfAvatar(nameOfAvatar); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); cookies.putString("nameOfAvatar", nameOfAvatar); cookies.flushSync(); } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java index 7401a593f358690bbbba93b1b49fb11847f72b61..1844f7eaed115a767b4730d989edee49906b438a 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 语言对话框 * - * @author BotLibre * @since 2021-05-10 */ public class LanguageDialogBuilder { @@ -75,13 +74,13 @@ public class LanguageDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.languages); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getLanguages()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer list, Component component, int ii, long ll) { - MainAbility.selectInfo = MainAbility.languages[ii]; // 赋值 选择的选项 - selectListener.selectLanguageItem(MainAbility.languages[ii] + ""); + MainAbility.setSelectInfo(MainAbility.getLanguages()[ii]); // 赋值 选择的选项 + selectListener.selectLanguageItem(MainAbility.getLanguages()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java index d8caef1fa97f65a4d41c50e0c281907e74135f3d..30962a3c1db6da45daa68f8bbc8e25cbcddd8582 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerDialogBuilder { @@ -75,13 +74,13 @@ public class SpinnerDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.types); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getTypes()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer listCon, Component component, int ii, long ll) { - MainAbility.type = MainAbility.types[ii]; // 赋值 选择的选项 - selectListener.selectItem(MainAbility.types[ii] + ""); + MainAbility.setType(MainAbility.getTypes()[ii]); // 赋值 选择的选项 + selectListener.selectItem(MainAbility.getTypes()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/Config.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/Config.java index f23dd45cf912457f7ad60fc0c8c07739b6cd4e34..57de1b2821a2984ede879e133b34b1f17034058c 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/Config.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/Config.java @@ -29,7 +29,7 @@ public class Config implements Cloneable { public String user; public String token; public String instance; - public String type; + public String supertype; public Object clone() { try { @@ -60,7 +60,7 @@ public class Config implements Cloneable { this.user = element.getAttribute("user"); this.token = element.getAttribute("token"); this.instance = element.getAttribute("instance"); - this.type = element.getAttribute("type"); + this.supertype = element.getAttribute("type"); } public void writeCredentials(StringWriter writer) { @@ -70,8 +70,8 @@ public class Config implements Cloneable { if (this.token != null && this.token.length() > 0) { writer.write(" token=\"" + this.token + "\""); } - if (this.type != null && !this.type.equals("")) { - writer.write(" type=\"" + this.type + "\""); + if (this.supertype != null && !this.supertype.equals("")) { + writer.write(" type=\"" + this.supertype + "\""); } if (this.instance != null && !this.instance.equals("")) { writer.write(" instance=\"" + this.instance + "\""); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java index 5c2f8ec2484e3fcead083e350e1e2e1e0d549590..6b35eee849d3c4dedf577bffc32180f31fbc7100 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java @@ -22,6 +22,7 @@ import org.w3c.dom.NodeList; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; +import java.util.Objects; /** @@ -63,6 +64,11 @@ public class ForumPostConfig extends Config { return false; } + @Override + public int hashCode() { + return Objects.hash(id, topic, summary, details, detailsText, forum, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isFeatured, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, replyCount, parent, avatar, replies); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java index 3fbf4d18ea42b341a401b970e65c9c898d821d83..5a9c0a4c852648eb2802aa73bcf15548e9ea9833 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java @@ -24,6 +24,7 @@ import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; /** @@ -62,7 +63,12 @@ public class IssueConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, title, priority, summary, details, detailsText, tracker, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isPriority, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, avatar); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java index 4082916a644d1b7278f5b2e55fdd62403752231d..1db85052b5598f7e87e9fc7ba4fe10bb020c6f84 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java @@ -16,6 +16,7 @@ package org.botlibre.sdk.config; import java.io.StringWriter; +import java.util.Objects; import ohos.utils.zson.ZSONException; import ohos.utils.zson.ZSONObject; @@ -70,6 +71,11 @@ public class ResponseConfig extends Config { return super.equals(object); } + @Override + public int hashCode() { + return Objects.hash(questionId, responseId, question, response, previous, onRepeat, label, topic, keywords, required, emotions, actions, poses, noRepeat, requirePrevious, requireTopic, flagged, correctness, command); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); @@ -152,7 +158,7 @@ public class ResponseConfig extends Config { this.emotions = element.getAttribute("emotions"); this.actions = element.getAttribute("actions"); this.poses = element.getAttribute("poses"); - this.type = element.getAttribute("type"); + this.supertype = element.getAttribute("type"); this.correctness = element.getAttribute("correctness"); if (element.getAttribute("noRepeat") != null) { this.noRepeat = Boolean.valueOf(element.getAttribute("noRepeat")); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java index 885e8a63b0661ef12e76043ba4f9367767b54069..62cde2c6241a43b72d597e1a1e04997c40a29265 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java @@ -20,6 +20,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import java.io.StringWriter; +import java.util.Objects; /** * DTO for XML user creation config. @@ -70,6 +71,11 @@ public class UserConfig extends Config { return this.user != null && this.user.equals(((UserConfig)object).user); } + @Override + public int hashCode() { + return Objects.hash(password, newPassword, hint, name, showName, email, website, bio, over18, avatar, connects, bots, posts, messages, forums, scripts, graphics, avatars, domains, channels, joined, lastConnect, type, isFlagged, flaggedReason); + } + public void parseXML(Element element) { this.user = element.getAttribute("user"); this.name = element.getAttribute("name"); diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java index a183e1306868ef0b0297301a572b6173d4419be1..3c7e43a28ec6b3d14deb4907f6c019c7857e18e1 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java @@ -34,7 +34,7 @@ import java.util.Map; * @since 2021-04-16 */ public class MicroConnection extends SDKConnection implements TextListener { - private WebMediumConfig config; + // private WebMediumConfig config; protected Map activeBots = new HashMap(); /** * message @@ -43,7 +43,7 @@ public class MicroConnection extends SDKConnection implements TextListener { /** * bot */ - public static Bot bot; + private static Bot bot; /** * Create a micro/offline SDK connection. @@ -74,8 +74,6 @@ public class MicroConnection extends SDKConnection implements TextListener { * @return config */ public T fetch(T config) { - this.config = config; - MicroMemory.storageFileName = config.name; if (!(config instanceof InstanceConfig)) { return super.fetch(config); } @@ -89,6 +87,5 @@ public class MicroConnection extends SDKConnection implements TextListener { */ public void sendMessage(TextOutput message) { this.message = message; - notifyAll(); } } \ No newline at end of file diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java index bce9ffe8c242a71cc0aa5b3ac96ba64fb6084abd..0d2563939d55dad1304e1a72365ab87737b6f8bf 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java @@ -36,7 +36,6 @@ import java.util.concurrent.atomic.AtomicInteger; * @param * @param * @param - * @author:hhh * @since 2021-05-08 */ public abstract class AsyncTask { @@ -82,7 +81,7 @@ public abstract class AsyncTask { protected void done() { super.done(); try { - postResult(get()); + postResult(super.get()); } catch (InterruptedException | ExecutionException e) { e.getMessage(); } @@ -118,7 +117,6 @@ public abstract class AsyncTask { /** * 可以回调的一些函数 */ - @MainThread protected void onPreExecute() { } @@ -135,14 +133,12 @@ public abstract class AsyncTask { * * @param result */ - @MainThread protected void onPostExecute(Result result) { } /** * onCancelled */ - @MainThread protected void onCancelled() { } @@ -151,14 +147,12 @@ public abstract class AsyncTask { * * @param progress */ - @MainThread protected void onProgressUpdate(Progress... progress) { } /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ private static class InnerUiHandler extends EventHandler { @@ -198,7 +192,6 @@ public abstract class AsyncTask { /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ public enum Status { @@ -262,7 +255,6 @@ public abstract class AsyncTask { * * @param * @param - * @author:hello * @since 2021-04-25 */ private abstract static class WorkRunnable implements Callable { @@ -276,7 +268,6 @@ public abstract class AsyncTask { * InnerUiHandler * * @param - * @author:hello * @since 2021-04-25 */ private static class AsyncTaskResult { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java index 2038bcd9f3ab6f31ef3ed232145ee810afff36f1..63627c1e327c2fae500dff3b238b6e5d829fbc67 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/Constant.java @@ -18,7 +18,6 @@ package org.botlibre.sdk.util; /** * 常量工具类 * - * @author: ColorPicker * @since 2021-04-16 */ public final class Constant { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java index 9629cb0ba876eae2c207eba41ac2a4fb6a79441b..1ef2134a46013a0cd655657d0b6a06d492ce86fd 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java @@ -21,7 +21,6 @@ import ohos.hiviewdfx.HiLogLabel; /** * Log工具类 * - * @author:turnlayout * @since 2021-04-16 */ public final class LogUtils { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java deleted file mode 100644 index 22487dec32617bd1033c3ac26a49d2f9ebedf86a..0000000000000000000000000000000000000000 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/MainThread.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.CLASS; - -/** - * 注解 - * - * @author:turnlayout - * @since 2021-04-16 - */ -@Documented -@Retention(CLASS) -@Target({METHOD, CONSTRUCTOR, TYPE, PARAMETER}) -public @interface MainThread { -} diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java index d98fdc2b0dc053c102ce53400fabd58f5cb962d8..518720442318ce7324b8c6cd609785d91e9fcfb9 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java @@ -23,7 +23,6 @@ import ohos.data.preferences.Preferences; /** * PreferencesUtils * - * @author:username * @since 2021-05-10 */ public class PreferencesUtils { diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java deleted file mode 100644 index 01cbef0229d910b8d378736f00c67bee32cf80cd..0000000000000000000000000000000000000000 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import ohos.agp.components.AttrSet; -import ohos.agp.components.element.Element; -import ohos.agp.components.element.ElementScatter; -import ohos.agp.components.element.PixelMapElement; -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.global.resource.RawFileEntry; -import ohos.global.resource.Resource; -import ohos.global.resource.ResourceManager; -import ohos.global.resource.WrongTypeException; -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; - -import java.io.IOException; -import java.util.Optional; - -/** - * ResUtil工具类 - * - * @author:turnlayout - * @since 2021-04-16 - */ -public class ResUtil { - private ResUtil() { - } - - /** - * get the path from id - * - * @param context the context - * @param id - * @return the path from id - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - return path; - } - return path; - } - - /** - * get the color - * - * @param context the context - * @param id - * @return the color - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get string - * - * @param context the context - * @param id - * @return string of the given id - */ - public static String getString(Context context, int id) { - String result = ""; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getString(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * getPreferences - * - * @param context - * @param id - * @param format - * @return str - */ - public static String getString(Context context, int id, Object... format) { - return String.format(getString(context, id), format); - } - - /** - * get the pixel map - * - * @param context the context - * @param id - * @return the pixel map - */ - public static Optional getPixelMap(Context context, int id) { - String path = getPathById(context, id); - if (path == null || path.length() <= 0) { - return Optional.empty(); - } - RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); - ImageSource.SourceOptions options = new ImageSource.SourceOptions(); - options.formatHint = "image/png"; - ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); - try { - Resource asset = assetManager.openRawFile(); - ImageSource source = ImageSource.create(asset, options); - return Optional.ofNullable(source.createPixelmap(decodingOptions)); - } catch (IOException e) { - return Optional.empty(); - } - } - - /** - * get the Pixel Map Element - * - * @param context the context - * @param resId - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * getElement - * - * @param context - * @param resId - * @return Element - */ - public static Element getElement(Context context, int resId) { - return ElementScatter.getInstance(context).parse(resId); - } - - /** - * getColorValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getColorValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getColorValue().getValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getDimensionValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getDimensionValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getIntValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getIntegerValue(); - if (value != 0) { - return value; - } - return defaultValue; - } -} - diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java index 8880a78eb06e636d858ac29e14d16ef6c4e0de22..8c9a674b0611ac9b4578cdceb9776a58258d3def 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java @@ -15,39 +15,33 @@ package org.botlibre.sdk.util; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.element.Element; +import ohos.aafwk.ability.Ability; +import ohos.agp.components.Button; +import ohos.agp.components.Checkbox; +import ohos.agp.components.ComponentState; import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.components.element.VectorElement; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; -import ohos.agp.utils.Rect; +import ohos.agp.components.element.StateElement; import ohos.app.Context; -import ohos.global.resource.*; -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; +import ohos.global.resource.NotExistException; +import ohos.global.resource.RawFileEntry; +import ohos.global.resource.Resource; +import ohos.global.resource.ResourceManager; +import ohos.global.resource.WrongTypeException; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; -import ohos.media.image.common.PixelFormat; -import ohos.media.image.common.Size; +import org.botlibre.sdk.ResourceTable; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; /** * 资源工具类 * - * @author:hello * @since 2021-04-25 */ -public class ResUtils { +public final class ResUtils { private static final String TAG = "ResUtil"; - private static final int CONSTANT = 160; + private static final float CONSTANT = 160; private ResUtils() { } @@ -59,19 +53,8 @@ public class ResUtils { * @param vp vp * @return px */ - public static int vpToPx(Context context, float vp) { - return (int) (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp); - } - - /** - * px转vp - * - * @param context 上下文 - * @param px px - * @return vp - */ - public static int pxTovp(Context context, float px) { - return (int) (px / (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT)); + public static float vpToPx(Context context, float vp) { + return context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp; } /** @@ -80,285 +63,65 @@ public class ResUtils { * @param context 上下文 * @return 屏幕的宽,单位px */ - public static int getScreenWidth(Context context) { + public static float getScreenWidth(Context context) { return vpToPx(context, context.getResourceManager().getDeviceCapability().width); } /** - * 获取屏幕的高 - * - * @param context 上下文 - * @return 屏幕的高,单位px - */ - public static int getScreenHeight(Context context) { - return vpToPx(context, context.getResourceManager().getDeviceCapability().height); - } - - /** - * 通过资源id获取路径 - * - * @param context 上下文 - * @param id 资源id - * @return 资源路径 - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - LogUtils.e("getPathById -> get null context"); - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getPathById -> get null ResourceManager"); - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - LogUtils.e("getPathById: " + e.getMessage()); - } - return path; - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static Color getNewColor(Context context, int id) { - return new Color(getColor(context, id)); - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - LogUtils.e("getColor -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getColor -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getColor: " + e.getMessage()); - } - return result; - } - - /** - * 通过资源id获取尺寸 - * - * @param context 上下文 - * @param id 资源Id - * @return 尺寸 - */ - public static float getDimen(Context context, int id) { - float result = 0; - if (context == null) { - LogUtils.e("getDimen -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getDimen: " + e.getMessage()); - } - return result; - } - - /** - * getBoolean - * - * @param context the context - * @param id the id - * @return get the boolean dimen value - */ - public static boolean getBoolean(Context context, int id) { - boolean result = false; - if (context == null) { - LogUtils.e("getBoolean -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException e) { - LogUtils.e("getBoolean -> IOException"); - } catch (NotExistException e) { - LogUtils.e("getBoolean -> NotExistException"); - } catch (WrongTypeException e) { - LogUtils.e("getBoolean -> WrongTypeException"); - } - return result; - } - - /** - * get string + * 设置button背景 * - * @param context the context - * @param id the string id - * @return string of the given id + * @param button + * @param resId */ - public static String getString(Context context, int id) { - String result = ""; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null ResourceManager"); - return result; - } + public static void setBackground(Button button, int resId) { + Resource bgResource = null; + button.setBackground(null); try { - result = manager.getElement(id).getString(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> WrongTypeException"); + bgResource = button.getResourceManager().getResource(resId); + PixelMapElement pixBg = new PixelMapElement(bgResource); + button.setAroundElements(pixBg, null, null, null); + } catch (IOException | NotExistException e) { + e.getMessage(); } - return result; } /** - * get the string array + * 设置button背景 * - * @param context the context - * @param id the string array id - * @return the string array + * @param ability + * @param checkbox */ - public static String[] getStringArray(Context context, int id) { - String[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getStringArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> WrongTypeException"); - } - return result; + public static void setCheckboxBg(Ability ability, Checkbox checkbox) { + StateElement stateElement = new StateElement(); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_checked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_unchecked)); + checkbox.setButtonElement(stateElement); } /** - * get the int - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int getInt(Context context, int id) { - int result = 0; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getInteger(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> WrongTypeException"); - } - return result; - } - - /** - * get the int array - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int[] getIntArray(Context context, int id) { - int[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> WrongTypeException"); - } - return result; - } - - /** - * get the vector drawable + * get the Pixel Map Element * * @param context the context - * @param id the drawable id - * @return the vector drawable + * @param resId + * @return the Pixel Map Element */ - public static VectorElement getVectorDrawable(Context context, int id) { - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getVectorDrawable -> get null context"); - return null; - } - return new VectorElement(context, id); + public static PixelMapElement getPixelMapDrawable(Context context, int resId) { + Optional optional = getPixelMap(context, resId); + return optional.map(PixelMapElement::new).orElse(null); } /** * get the pixel map * * @param context the context - * @param id the id + * @param id * @return the pixel map */ public static Optional getPixelMap(Context context, int id) { String path = getPathById(context, id); - if (path.isEmpty()) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> get empty path"); + if (path == null || path.length() <= 0) { return Optional.empty(); } RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); @@ -370,223 +133,31 @@ public class ResUtils { ImageSource source = ImageSource.create(asset, options); return Optional.ofNullable(source.createPixelmap(decodingOptions)); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> IOException"); + return Optional.empty(); } - return Optional.empty(); } /** - * get the Pixel Map Element + * get the path from id * * @param context the context - * @param resId the res id - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement + * @param id + * @return the path from id */ - public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle, - float sweepAngle) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } - - /** - * get the Element - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param rect the rect - * @return the Element - */ - public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.OVAL); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - element.setBounds(rect); - return element; - } - - /** - * get the Element - * - * @param inside the inside color - * @param rect the rect - * @return the Element - */ - public static Element getCustomRectGradientDrawable(Color inside, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.RECTANGLE); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setBounds(rect); - return element; - } - - /** - * 根据Resource获取背景(图片) - * - * @param resource 资源 - * @return 位图背景 - * @throws IOException - * @throws NotExistException - */ - public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException { - return new PixelMapElement(preparePixelmap(resource)); - } - - /** - * 根据Resource获取位图 - * - * @param resource 资源 - * @return 位图 - * @throws IOException - * @throws NotExistException - * @throws FileNotFoundException - */ - public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException { - ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions(); - ImageSource imageSource = null; - try { - imageSource = ImageSource.create(readResource(resource), srcOpts); - } finally { - close(resource); - } - if (imageSource == null) { - throw new FileNotFoundException(); - } - ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions(); - decodingOpts.desiredSize = new Size(0, 0); - decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0); - decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888; - - PixelMap pixelmap = imageSource.createPixelmap(decodingOpts); - return pixelmap; - } - - private static void close(Resource resource) { - if (resource != null) { - try { - resource.close(); - } catch (IOException e) { - Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage()); - } - } - } - - private static byte[] readResource(Resource resource) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bArr = new byte[1024]; - while (true) { - try { - int read = resource.read(bArr, 0, 1024); - if (read == -1) { - break; - } - byteArrayOutputStream.write(bArr, 0, read); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } finally { - try { - byteArrayOutputStream.close(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } - } - } - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource finish"); - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource len: " + byteArrayOutputStream.size()); - return byteArrayOutputStream.toByteArray(); - } - - /** - * rgb颜色值转换为rgba的ShapeElement - * - * @param rgbColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement6(int rgbColor) { - if (rgbColor < 0 && rgbColor >= -0xffffff) { - rgbColor = rgbColor + 0xffffff + 1; + public static String getPathById(Context context, int id) { + String path = ""; + if (context == null) { + return path; } - if (rgbColor > 0 && rgbColor <= 0xffffff) { - rgbColor = alphaColor(rgbColor, 1.0f); + ResourceManager manager = context.getResourceManager(); + if (manager == null) { + return path; } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbColor)); - return shapeElement; - } - - /** - * rgb颜色值转换为rgba - * - * @param rgbColor 颜色值 - * @param alpha 透明度 - * @return int - */ - public static int alphaColor(int rgbColor, float alpha) { - if (rgbColor < 0) { - rgbColor = rgbColor + 0xffffff + 1; + try { + path = manager.getMediaPath(id); + } catch (IOException | NotExistException | WrongTypeException e) { + return path; } - int rgb = Math.max(0, rgbColor) << 8; - int al = (int) (alpha * 255); - return rgb + al; - } - - /** - * 颜色值rgba转换为ShapeElement - * - * @param rgbaColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement8(int rgbaColor) { - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbaColor)); - return shapeElement; + return path; } } diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java deleted file mode 100644 index 898266f217f2e0c75fb7528212784016618b8e60..0000000000000000000000000000000000000000 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import org.botlibre.sdk.ResourceTable; -import ohos.aafwk.ability.Ability; -import ohos.agp.components.Button; -import ohos.agp.components.Checkbox; -import ohos.agp.components.ComponentState; -import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.StateElement; -import ohos.global.resource.NotExistException; -import ohos.global.resource.Resource; - -import java.io.IOException; - -/** - * ShapeUtils - * - * @author:username - * @since 2021-05-13 - */ -public class ShapeUtils { - private ShapeUtils() { - } - - /** - * 设置button背景 - * - * @param button - * @param resId - */ - public static void setBackground(Button button, int resId) { - Resource bgResource = null; - button.setBackground(null); - try { - bgResource = button.getResourceManager().getResource(resId); - PixelMapElement pixBg = new PixelMapElement(bgResource); - button.setAroundElements(pixBg, null, null, null); - } catch (IOException | NotExistException e) { - e.getMessage(); - } - } - - /** - * 设置button背景 - * - * @param ability - * @param checkbox - */ - public static void setCheckboxBg(Ability ability, Checkbox checkbox) { - StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_unchecked)); - checkbox.setButtonElement(stateElement); - } -} diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java deleted file mode 100644 index fb4b29d6d62e182354097aa0da2282475f66768d..0000000000000000000000000000000000000000 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/TextStream.java +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Provides a useful text stream class. - */ - -public class TextStream { - public static final String WHITESPACE =" \t\n\r\f"; - public static final String HTTP =" \t\n\r\f\""; - public static final String TOKENS =" \t\n\r\f.,:;!()?[]{}+=^&*\"`~|/\\<>"; - public static final String TERMINATORS =".?!。"; - public static Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); - public static Set IGNORABLE = new HashSet(Arrays.asList(new String[]{"'","`", "\"", ","})); - - /** - * The text being streamed. - */ - protected String text; - - /** - * The current stream index into the text. - */ - protected int index; - - public TextStream(String text) { - this.index = 0; - this.text = text; - } - - public void reset() { - this.index = 0; - } - - public char last() { - if (this.index <= 1) { - return (char)0; - } - return this.text.charAt(this.index - 2); - } - - public char current() { - if (this.index <= 0) { - return (char)0; - } - return this.text.charAt(this.index - 1); - } - - public char peekPrevious() { - if (this.index <= 1) { - return (char)0; - } - return this.text.charAt(this.index - 2); - } - - public char peek() { - if (atEnd()) { - return (char)-1; - } - return this.text.charAt(this.index); - } - - public int peekCodePoint() { - if (atEnd()) { - return (int)-1; - } - return this.text.codePointAt(this.index); - } - - public char next() { - if (this.index >= this.text.length()) { - return (char)-1; - } - char next = this.text.charAt(this.index); - this.index++; - return next; - } - - public char previous() { - this.index--; - char previous = current(); - return previous; - } - - public void skip() { - if (this.index >= this.text.length()) { - return; - } - this.index++; - } - - public void skip(int count) { - this.index = Math.min(this.index + count, this.text.length()); - } - - public void backup(int count) { - this.index = Math.max(this.index - count, 0); - } - - public void backup() { - this.index--; - } - - public String peek(int count) { - int start = this.index; - int end = Math.min(this.index + count, this.text.length()); - return this.text.substring(start, end); - } - - public String previous(int count) { - int end = this.index - 2; - if (end <= 0) { - return ""; - } - int start = Math.max(end - count, 0); - return this.text.substring(start, end); - } - - public String next(int count) { - int start = this.index; - this.index = Math.min(this.index + count, this.text.length()); - return this.text.substring(start, this.index); - } - - public boolean atEnd() { - return this.index >= this.text.length(); - } - - public boolean atStart() { - return this.index == 0; - } - - public String upTo(char token) { - return upTo(token, false); - } - - public void skipTo(char token) { - skipTo(token, false); - } - - public String upToEnd() { - int start = this.index; - this.index = this.text.length(); - return this.text.substring(start, this.index); - } - - public String upTo(char token, boolean including) { - return upTo(token, including, false); - } - - public String upTo(char token, boolean including, boolean resetIfNotFound) { - int start = this.index; - boolean found = skipTo(token, including); - if (resetIfNotFound && !found) { - this.index = start; - return ""; - } - return this.text.substring(start, this.index); - } - - public boolean skipTo(char token, boolean including) { - boolean found = false; - while (!atEnd()) { - if (peek() == token) { - found = true; - break; - } - skip(); - } - if (found && including) { - skip(); - } - return found; - } - - public void backupTo(char token) { - backupTo(token, false); - } - - public void backupTo(char token, boolean including) { - boolean found = false; - while (this.index > 0) { - if (current() == token) { - found = true; - break; - } - backup(); - } - if (found && including) { - backup(); - } - } - - public String upToAny(String tokens) { - return upToAny(tokens, false); - } - - public String upToAny(String tokens, boolean including) { - int start = this.index; - skipToAny(tokens, including); - return this.text.substring(start, this.index); - } - - public void skipToAny(String tokens) { - skipToAny(tokens, false); - } - - public void skipToAny(String tokens, boolean including) { - boolean found = false; - while (!atEnd()) { - if (tokens.indexOf(peek()) != -1) { - found = true; - break; - } - skip(); - } - if (found && including) { - skip(); - } - } - - public String upToAll(String tokens) { - return upToAll(tokens, false); - } - - public String upToAll(String tokens, boolean including) { - return upToAll(tokens, including, false); - } - - public String upToAll(String tokens, boolean including, boolean resetIfNotFound) { - int start = this.index; - boolean found = skipToAll(tokens, including); - if (resetIfNotFound && !found) { - this.index = start; - return ""; - } - return this.text.substring(start, this.index); - } - - public void skipToAll(String tokens) { - skipToAll(tokens, false); - } - - public boolean skipToAll(String tokens, boolean including) { - int tokenIndex = 0; - boolean found = false; - while (!atEnd()) { - if (peek() == tokens.charAt(tokenIndex)) { - tokenIndex++; - if (tokenIndex == tokens.length()) { - found = true; - break; - } - } else { - tokenIndex = 0; - } - skip(); - } - if (found) { - if (including) { - skip(); - } else { - this.index = index - (tokens.length() - 1); - } - } - return found; - } - - public void backupToAll(String tokens) { - backupToAll(tokens, false); - } - - public void backupToAll(String tokens, boolean including) { - int tokenIndex = 1; - int length = tokens.length(); - boolean found = false; - while (this.index > 0) { - if (current() == tokens.charAt(length - tokenIndex)) { - if (tokenIndex == tokens.length()) { - found = true; - break; - } - tokenIndex++; - } else { - tokenIndex = 1; - } - backup(); - } - if (found) { - if (including) { - backup(); - } else { - this.index = index + (length - 1); - } - } - } - - public void backupToAny(String tokens) { - backupToAny(tokens, false); - } - - public void backupToAny(String tokens, boolean including) { - boolean found = false; - while (!atStart()) { - if (tokens.indexOf(peekPrevious()) != -1) { - found = true; - break; - } - backup(); - } - if (found && including) { - backup(); - } - } - - public String peekWord() { - int position = this.index; - String word = nextWord(); - this.index = position; - return word; - } - - public List allWords() { - List words = new ArrayList(); - while (!atEnd()) { - String word = nextWord(); - if (word != null) { - words.add(word); - } - } - return words; - } - - public List csv() { - List words = new ArrayList(); - skipWhitespace(); - while (!atEnd()) { - String word = upTo(','); - if (!atEnd()) { - skip(); - skipWhitespace(); - } - if ((word != null) && !word.trim().equals("")) { - words.add(word); - } - } - return words; - } - - public String peekPreviousWord() { - int original = this.index; - backupWhitespace(); - int start = this.index; - if (atStart()) { - return null; - } - char current = current(); - if ((TOKENS.indexOf(current) != -1) || (isWordSymbol(current))) { - previous(); - String word = String.valueOf(current); - this.index = original; - return word; - } - backupToAny(TOKENS); - String word = this.text.substring(Math.max(this.index - 1, 0), start); - this.index = original; - return word; - } - - public boolean isWordSymbol(char character) { - Character.UnicodeBlock block = Character.UnicodeBlock.of(character); - return ((block == Character.UnicodeBlock.HIRAGANA) - || (block == Character.UnicodeBlock.KATAKANA) - || (block == Character.UnicodeBlock.HANGUL_SYLLABLES) - || (block == Character.UnicodeBlock.HANGUL_JAMO)) - && !Character.isDigit(character); - } - - public String nextQuotes() { - if (atEnd()) { - return ""; - } - int start = this.index; - skipQuotes(); - int end = this.index - 1; - if (atEnd() && current() != '"') { - end = this.index; - } - String quotes = this.text.substring(start, end); - return quotes; - } - - public String nextQuotesExcludeDoubleQuote() { - String quotes = nextQuotes(); - if (quotes.contains("\"\"")) { - quotes = quotes.replace("\"\"", "\""); - } - return quotes; - } - - public void skipQuotes() { - if (atEnd()) { - return; - } - char next = next(); - char peek = peek(); - while (!atEnd() && ((next != '"') || (peek == '"'))) { - if ((next == '"') && (peek == '"')) { - skip(); - } - if (next == '{') { - skipBrackets(); - } - next = next(); - peek = peek(); - } - } - - public void skipBrackets() { - if (atEnd()) { - return; - } - char next = next(); - while (!atEnd() && (next != '}')) { - if (next == '"') { - skipQuotes(); - } - next = next(); - } - } - - public String nextWord() { - skipWhitespace(); - if (atEnd()) { - return null; - } - //int peek = peekCodePoint(); - char peek = peek(); - boolean isSign = (peek == '-') || (peek == '+'); - // Check for "1-1" vs "1 - -1" - if (isSign && !atStart()) { - backup(); - char previous = peek(); - if (Character.isLetterOrDigit(previous)) { - skip(); - skip(); - return String.valueOf(peek); - } - skip(); - } - if (isWordSymbol(peek) || (!Character.isLetterOrDigit(peek) && peek != '_' && peek != '@' && !isSign)) { - skip(); - Character.UnicodeBlock block = Character.UnicodeBlock.of(peek); - if (block == Character.UnicodeBlock.HIGH_SURROGATES) { - skip(); - return this.text.substring(this.index - 2, this.index); - } - return String.valueOf(peek); - } - // Check url. - if (peek == 'h') { - if (peek(7).equals("http://") || peek(8).equals("https://")) { - return upToAny(HTTP); - } - } - int start = this.index; - boolean wasDigit = Character.isDigit(peek); - skip(); - while (!atEnd()) { - //peek = peekCodePoint(); - peek = peek(); - boolean isDigit = Character.isDigit(peek); - if (isWordSymbol(peek)) { - break; - } - // "-1" is ok - if (isSign && !isDigit) { - break; - } else { - // Allow "1.1", "1,000", "ab-ba", "ab_ba" - if (!Character.isLetter(peek) && !isDigit && (peek != '_')) { - if (wasDigit) { - if ((peek != '.') && (peek != ',') && (peek != '@')) { - break; - } - } else { - if ((peek != '-') && (peek != '_') && (peek != '@') && (peek != '.')) { - break; - } - } - } - } - wasDigit = isDigit; - skip(); - // Could have been "1.", "1.a" - if ((((peek == '.') && !Character.isLetter(peek())) || (peek == ',')) && !Character.isDigit(peek())) { - backup(); - break; - } - isSign = false; - } - return this.text.substring(start, this.index); - } - - public void skipWord() { - skipWhitespace(); - if (atEnd()) { - return; - } - if (TOKENS.indexOf(peek()) != -1) { - skip(); - } - // Check url. - if (peek() == 'h') { - if (peek(7).equals("http://")) { - skipToAny(WHITESPACE); - } - } - skipToAny(TOKENS); - } - - public String nextSentence() { - skipWhitespace(); - if (atEnd()) { - return null; - } - int start = this.index; - skipToAny(TERMINATORS, true); - while (!atEnd()) { - char peek = peek(); - boolean done = WHITESPACE.indexOf(peek) != -1; - if (done) { - if (current() != '.') { - break; - } - backup(); - String word = peekPreviousWord(); - skip(); - if (ABBREVIATIONS.contains(word.toLowerCase()) - || ((word.length() == 1) && (Character.isUpperCase(word.charAt(0))))) { - done = false; - } else { - break; - } - } else if (isWordSymbol(peek)) { - break; - } - skipToAny(TERMINATORS, true); - } - return this.text.substring(start, this.index); - } - - public String nextWhitespace() { - int start = this.index; - while (!atEnd() && (WHITESPACE.indexOf(peek()) != -1)) { - skip(); - } - return this.text.substring(start, this.index); - } - - public boolean skipWhitespace() { - boolean found = false; - while (!atEnd() && (Character.isWhitespace(peek()))) { - skip(); - found = true; - } - return found; - } - - public void backupWhitespace() { - while (!atStart() && (WHITESPACE.indexOf(current()) != -1)) { - backup(); - } - } - - public String nextLine() { - return upToAll("\n", true); - } - - public String currentLine() { - int position = this.index; - backupToAll("\n"); - String line = nextLine(); - this.index = position; - return line; - } - - public int currentLineNumber() { - int position = this.index; - this.index = 0; - int count = 0; - int last = this.index; - while (this.index < position) { - skipLine(); - if (this.index < position) { - count++; - } - if (this.index == last) { - break; - } - last = this.index; - } - this.index = position; - return count + 1; - } - - public int currentLineColumn() { - int position = this.index; - backupToAll("\n"); - int column = position - this.index; - this.index = position; - return column + 1; - } - - public void skipLine() { - skipToAll("\n", true); - } - - public int getPosition() { - return index; - } - - public void setPosition(int index) { - this.index = index; - } - - public String getText() { - return text; - } - - public String toString() { - return peek(text.length()); - } - -} \ No newline at end of file diff --git a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java index 8a7995bd5c02b4c8de8136000b4cafe7970d9b2b..d95dd3595242a802e7397a6dec6ee6883d50b30f 100644 --- a/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java +++ b/PizzaBotOffline/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java @@ -27,7 +27,6 @@ import ohos.app.Context; /** * ToastUtils * - * @author:258767-shengyu * @since 2021-04-20 */ public class ToastUtils { diff --git a/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java b/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java deleted file mode 100644 index 905e2e38c5c233d359f4c2af025d853f4fd6ac0e..0000000000000000000000000000000000000000 --- a/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk; - -import ohos.aafwk.ability.Ability; -import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry; -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; -import org.botlibre.sdk.util.LogUtils; -import org.botlibre.sdk.util.ResUtils; -import org.junit.Assert; -import org.junit.Test; - -/** - * 单元测试类 - * - * @author BotLibre - * @since 2021-05-25 - */ -public class MainAbilityTest { - private static final HiLogLabel LABEL_LOG = new HiLogLabel(10043, 0xD000f00, "MainAbility"); - Ability ability = AbilityDelegatorRegistry.getAbilityDelegator().getCurrentTopAbility(); - - @Test - public void onStart() { - LogUtils.d("HiLog","单元测试"); - int pxTovp = ResUtils.pxTovp(ability.getApplicationContext(),1); - Assert.assertEquals(0, pxTovp); - int height = ResUtils.getScreenHeight(ability.getApplicationContext()); - HiLog.info(LABEL_LOG,height + ""); - int width = ResUtils.getScreenWidth(ability.getApplicationContext()); - HiLog.info(LABEL_LOG,width + ""); - int color = ResUtils.getColor(ability.getApplicationContext(),-65536); - HiLog.info(LABEL_LOG,color + ""); - } -} \ No newline at end of file diff --git a/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/util/ResUtilsOhosTest.java b/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/util/ResUtilsOhosTest.java index 5f6ba2af33966d839624b447d327af64c5dc1302..9394905ff42143431f4918ade5d7311a1e2c0caf 100644 --- a/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/util/ResUtilsOhosTest.java +++ b/PizzaBotOffline/entry/src/ohosTest/java/org/botlibre/sdk/util/ResUtilsOhosTest.java @@ -5,7 +5,6 @@ import org.junit.Test; /** * ResUtilsOhosTest * - * @author:username * @since 2021-06-17 */ public class ResUtilsOhosTest { diff --git a/SantaBot/build.gradle b/SantaBot/build.gradle index eaa69ab6660caa5e71799dc98afc9a8394db0e6c..a4bbee50c84428507c792bf978676f0ff6fe17a8 100644 --- a/SantaBot/build.gradle +++ b/SantaBot/build.gradle @@ -2,17 +2,6 @@ apply plugin: 'com.huawei.ohos.app' ohos { - signingConfigs { - debug { - storeFile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.p12') - storePassword '000000186F2072CDBF4F29D6F1F0A082391252B4988AF3FE87F748FB333B24A91A4FB04349737F41' - keyAlias = 'debugKey' - keyPassword '00000018EC969D3028C3D7289509AB8E7AA74A5BFA61B700CB8351942CD39BC744D4C0C139153DC9' - signAlg = 'SHA256withECDSA' - profile file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_sdk_890086000102149657.p7b') - certpath file('C:\\Users\\258767-shengyu\\.ohos\\config\\auto_debug_890086000102149657.cer') - } - } compileSdkVersion 6 defaultConfig { compatibleSdkVersion 5 diff --git a/SantaBot/entry/src/main/config.json b/SantaBot/entry/src/main/config.json index a8729f7fb0c6be7ef628b859999529c28a6d9531..a897ffb847b137f72c1d8d7845813b328df5636a 100644 --- a/SantaBot/entry/src/main/config.json +++ b/SantaBot/entry/src/main/config.json @@ -114,24 +114,54 @@ "name": "ohos.permission.ACCESS_BIOMETRIC_INTERNAL" }, { + "name": "ohos.permission.READ_USER_STORAGE", "reason": "Read User Storage", - "name": "ohos.permission.READ_USER_STORAGE" + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Camera", - "name": "ohos.permission.READ_MEDIA" + "name": "ohos.permission.READ_MEDIA", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { - "reason": "Get Media", - "name": "ohos.permission.MEDIA_LOCATION" + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.WRITE_USER_STORAGE", - "reason": "get WRITE_USER_STORAGE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } }, { "name": "ohos.permission.MICROPHONE", - "reason": "get MICROPHONE" + "reason": "Read User Storage", + "usedScene": { + "ability": [ + "org.botlibre.sdk.MainAbility" + ], + "when": "inuse" + } } ] } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java index fa87008d9337394bdc61592cc11c48d5806d9798..1b2e369246c78a388e4bb12014769417654545b7 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/BOTlibreCredentials.java @@ -23,11 +23,9 @@ package org.botlibre.sdk; * http://www.botlibre.com */ public class BOTlibreCredentials extends Credentials { - public static String DOMAIN = "www.botlibre.com"; - //public static String DOMAIN = "192.168.0.21:9080"; - public static String APP = ""; - //public static String APP = "/botlibre"; - public static String PATH = "/rest/api"; + public static final String DOMAIN = "www.botlibre.com"; + public static final String APP = ""; + public static final String PATH = "/rest/api"; public BOTlibreCredentials(String applicationId) { this.host = DOMAIN; diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/MainAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/MainAbility.java index a6121e0b0be11bdb35a7104fc7863231b030620e..e12f87328d245af0c9450e76b70fa2932a3244bf 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/MainAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/MainAbility.java @@ -8,7 +8,6 @@ import ohos.agp.components.Component; import ohos.agp.components.DirectionalLayout; import ohos.agp.components.LayoutScatter; import ohos.agp.components.Text; -import ohos.agp.components.TextField; import ohos.agp.utils.Color; import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.dialog.CommonDialog; @@ -21,20 +20,15 @@ import ohos.app.Context; import ohos.data.preferences.Preferences; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; -import ohos.media.audio.AudioManager; -import ohos.media.audio.AudioRemoteException; import ohos.multimodalinput.event.TouchEvent; import ohos.security.SystemPermission; import ohos.utils.net.Uri; -import org.botlibre.knowledge.micro.MicroMemory; import org.botlibre.sdk.ability.BotSearchAbility; import org.botlibre.sdk.ability.CreateUserAbility; import org.botlibre.sdk.ability.HelpAbility; import org.botlibre.sdk.ability.LibreAbility; import org.botlibre.sdk.ability.ListTemplateView; import org.botlibre.sdk.ability.LoginAbility; -import org.botlibre.sdk.ability.actions.HttpGetInstancesAction; -import org.botlibre.sdk.ability.actions.HttpGetTemplatesAction; import org.botlibre.sdk.ability.adapter.SpinnerAdapter; import org.botlibre.sdk.ability.dialog.LanguageDialogBuilder; import org.botlibre.sdk.ability.dialog.SpinnerDialogBuilder; @@ -42,8 +36,6 @@ import org.botlibre.sdk.ability.listener.LanguageListener; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.ability.war.StartWarAbility; import org.botlibre.sdk.config.AvatarConfig; -import org.botlibre.sdk.config.AvatarMedia; -import org.botlibre.sdk.config.BotModeConfig; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.config.ChannelConfig; import org.botlibre.sdk.config.DomainConfig; @@ -75,29 +67,33 @@ import static ohos.agp.components.Component.HIDE; import static ohos.agp.components.Component.VISIBLE; import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; +/** + * MainAbility + * + * @since 2021-04-25 + */ public class MainAbility extends LibreAbility implements SelectListener, LanguageListener, Component.TouchEventListener { - public static final boolean DEBUG = false; - public static final boolean ADULT = false; + private static final boolean DEBUG = false; /** * Enter your application ID here. * You can get an application ID from any of the services websites (Bot Libre, Bot Libre for Business) */ - public static String applicationId = "enter your application id here"; + private static String applicationId = "enter your application id here"; /** * Configure your connection credentials here. * Choose which service provider you wish to connect to. */ - public static SDKConnection connection, localConnection, remoteConnection; + private static SDKConnection connection, localConnection, remoteConnection; /** * To launch into a specific domain, enter the domain id here. */ - public static String domainId = null; - public static DomainConfig domain; - public static String defaultType = "Bots"; - public static boolean showAds = true; + private static String domainId = null; + private static DomainConfig domain; + private static String defaultType = "Bots"; + private static boolean showAds = true; /** * Choose your service provider using the correct credentials. @@ -106,37 +102,30 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag localConnection = new MicroConnection(new BOTlibreCredentials(applicationId)); remoteConnection = new SDKConnection(new BOTlibreCredentials(applicationId)); connection = remoteConnection; - if (domainId != null) { - domain = new DomainConfig(); - domain.id = domainId; - connection.setDomain(domain); - } if (DEBUG) { showAds = false; connection.setDebug(true); } } - public static String WEBSITE = "https://www.botlibre.com"; + /** + * WEBSITEHTTPS + */ public static final String WEBSITEHTTPS = "https://www.botlibre.com"; - public static String SERVER = "botlibre.com"; /** * If you are building a single instance app, then you can set the instance id or name here, * and use this to launch it. */ - public static String launchInstanceId = ""; // i.e. "171" - public static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" - public static String website = "https://www.botlibre.com"; - public static String prefix = "Bot"; - public static String launchSelfScriptID = ""; - public static String launchGreetingScriptID = ""; + private static String launchInstanceId = ""; // i.e. "171" + private static String launchInstanceName = "Pizza Bot"; // i.e. "Help Bot" + private static String website = "https://www.botlibre.com"; /** * If you are building a single instance app, then you can set the launchType to * have this launch the bot, forum, or channel. */ - public static LaunchType launchType = LaunchType.Bot; + private static LaunchType launchType = LaunchType.Bot; @Override public void selectItem(String select) { @@ -156,92 +145,70 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag public boolean onTouchEvent(Component component, TouchEvent touchEvent) { switch (touchEvent.getAction()) { case TouchEvent.PRIMARY_POINT_DOWN: - // Check whether the user pressed on the pointer. -// execcontentinfo.setScrollable(true); -// notifyAll(); break; default: } return true; } - public enum LaunchType {Browse, Bot, Forum, Channel} + /** + * LaunchType + * + * @since 2021-04-25 + */ + private enum LaunchType {Bot, Forum, Channel} - public static boolean online = true; + private static boolean online = true; - public static boolean handsFreeSpeech = true; - public static boolean listenInBackground = false; - public static boolean micConfig = true; + private static boolean handsFreeSpeech = true; + private static boolean listenInBackground = false; + private static boolean micConfig = true; // selected image from the listView of the offline Templates bots - public static int offlineSelectedImage; - - public static boolean hasRequestAvatar; - public static boolean sound = true; - public static boolean disableVideo; - public static boolean webm = true; - public static boolean hd; - public static boolean deviceVoice; - public static boolean customVoice; - public static boolean translate; - - public static boolean offlineSpeech = false; - - public static GraphicConfig gInstance; - public static WebMediumConfig instance; - public static ForumPostConfig post; - public static IssueConfig issue; - public static UserConfig user; - public static UserConfig viewUser; - public static String type = "Bots"; - public static BotModeConfig botMode = new BotModeConfig(); - public static VoiceConfig voice = new VoiceConfig(); - public static LearningConfig learning = new LearningConfig(); - public static AvatarMedia avatarMedia; - public static ResponseConfig response; - public static ScriptSourceConfig script; - public static String conversation; - public static String template = ""; - public static String currentPhotoPath; - public static List templates; - public static Object[] tags; - public static Object[] categories; - public static Object[] forumTags; - public static Object[] forumPostTags; - public static Object[] forumCategories; - public static Object[] channelTags; - public static Object[] channelCategories; - public static Object[] avatarTags; - public static Object[] scriptTags; - public static Object[] scriptCategories; - public static Object[] avatarCategories; - public static int volume; - - public static String contentRating; - public static Object[] domainTags; - public static Object[] domainCategories; - - public static String nameOfAvatar; - - public static Object[] graphicTags; - public static Object[] graphicCategories; - public static boolean showImages = true; - public static BrowseConfig browse = null; - public static BrowseConfig browsePosts = null; - public static BrowseConfig browseIssues = null; - public static List instances = new ArrayList(); - public static List posts = new ArrayList(); - public static List issues = new ArrayList(); - public static List avatarMedias = new ArrayList(); - public static MainAbility current; - public static boolean browsing; - public static boolean searching; - public static boolean searchingPosts; - public static boolean searchingIssues; - public static boolean wasDelete; - public static boolean importingBotScript = false; - public static boolean importingBotLog = false; - public static String[] languages = new String[]{ + private static int offlineSelectedImage; + + private static boolean sound = true; + private static boolean disableVideo; + private static boolean webm = true; + private static boolean hd; + private static boolean deviceVoice; + private static boolean customVoice; + private static boolean translate; + + private static boolean offlineSpeech = false; + + private static WebMediumConfig instance; + private static ForumPostConfig post; + private static IssueConfig issue; + private static UserConfig user; + private static UserConfig viewUser; + private static String type = "Bots"; + private static VoiceConfig voice = new VoiceConfig(); + private static LearningConfig learning = new LearningConfig(); + private static ResponseConfig response; + private static ScriptSourceConfig script; + private static String conversation; + private static String template = ""; + private static List templates; + private static Object[] tags; + private static Object[] categories; + private static Object[] channelTags; + private static int volume; + + private static String contentRating; + + private static String nameOfAvatar; + + private static boolean showImages = true; + private static List instances = new ArrayList(); + private static List posts = new ArrayList(); + private static MainAbility current; + private static boolean browsing; + private static boolean searching; + private static boolean searchingPosts; + private static boolean importingBotScript = false; + private static boolean importingBotLog = false; + private static String[] languages = new String[]{ "Default", "af - Afrikaans", "sq - Albanian", "ar - Arabic", "hy - Armenian", "az - Azerbaijani", "ba - Bashkir", "eu - Basque", "be - Belarusian", "bn - Bengali", "bs - Bosnian", "bg - Bulgarian", @@ -254,172 +221,29 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag "tl - Tagalog", "tg - Tajik", "ta - Tamil", "tt - Tatar", "th - Thai", "tr - Turkish", "udm - Udmurt", "uk - Ukrainian", "ur - Urdu", "uz - Uzbek", "vi - Vietnamese", "cy - Welsh" }; - public static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; - public static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; - public static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - public static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; - public static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - public static String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; - public static String[] forkAccMode = new String[]{"Administrators", "Members", "Users", "Disabled"}; - public static String[] mediaAccessModes = new String[]{"Administrators", "Everyone", "Members", "Users", "Disabled"}; - public static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - public static String[] scriptLanguages = new String[]{"Self", "AIML", "Response List", "Chat Log", "CVS"}; - public static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - public static String[] responseTypes = new String[]{"conversations", "responses", "greetings", "default", "flagged"}; - public static String[] durations = new String[]{"all", "day", "week", "month"}; - public static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; - public static String[] responseRestrictions = new String[]{"", "exact", "keyword", "required", "topic", "label", "previous", - "repeat", "missing-keyword", "missing-required", "missing-topic", "patterns", "templates", "flagged", "corrections", - "emotions", "actions", "poses"}; - public static String[] voices = new String[]{ - "cmu-slt", - "cmu-slt-hsmm", - "cmu-bdl-hsmm", - "cmu-rms-hsmm", - "dfki-prudence", - "dfki-prudence-hsmm", - "dfki-spike", - "dfki-spike-hsmm", - "dfki-obadiah", - "dfki-obadiah-hsmm", - "dfki-poppy", - "dfki-poppy-hsmm", - "bits1-hsmm", - "bits3", - "bits3-hsmm", - "dfki-pavoque-neutral-hsmm", - "camille", - "camille-hsmm-hsmm", - "jessica_voice-hsmm", - "pierre-voice-hsmm", - "enst-dennys-hsmm", - "istc-lucia-hsmm", - "voxforge-ru-nsh", - "dfki-ot", - "dfki-ot-hsmm", - "cmu-nk", - "cmu-nk-hsmm" - }; - public static String[] voiceMods = new String[]{ - "default", "child", "whisper", "echo", "robot" - }; - public static String[] voiceNames = new String[]{ - "English : US : Female : SLT", - "English : US : Female : SLT (hsmm)", - "English : US : Male : BDL (hsmm)", - "English : US : Male : RMS (hsmm)", - "English : GB : Female : Prudence", - "English : GB : Female : Prudence (hsmm)", - "English : GB : Male : Spike", - "English : GB : Male : Spike (hsmm)", - "English : GB : Male : Obadiah", - "English : GB : Male : Obadiah (hsmm)", - "English : GB : Female : Poppy", - "English : GB : Female : Poppy (hsmm)", - "German : DE : Female : Bits1 (hsmm)", - "German : DE : Male : Bits3", - "German : DE : Male : Bits3 (hsmm)", - "German : DE : Male : Pavoque (hsmm)", - "French : FR : Female : Camille", - "French : FR : Female : Camille (hsmm)", - "French : FR : Female : Jessica (hsmm)", - "French : FR : Male : Pierre (hsmm)", - "French : FR : Male : Dennys (hsmm)", - "Italian : IT : Male : Lucia (hsmm)", - "Russian : RU : Male : NSH (hsmm)", - "Turkish : TR : Male : OT", - "Turkish : TR : Male : OT (hsmm)", - "Telugu : TE : Female : NK", - "Telugu : TE : Female : NK (hsmm)" - }; - + private static String[] servers = new String[]{"www.botlibre.com", "twitter.botlibre.com", "www.botlibre.biz", "www.livechatlibre.com", "www.forumslibre.com"}; + private static String[] types = new String[]{"Bots", "Avatars", "Scripts", "Forums", "Live Chat", "Graphics", "Domains", "Chat Bot Wars"}; + private static String[] contentRatings = new String[]{"Everyone", "Teen", "Mature"}; + private static String[] inputTypes = new String[]{"all", "chat", "tweet", "post", "directmessage", "email"}; Menu menu; - public static int templateID; - public Button spin; - public Button createInstanceButton; - public Button browseButton; - public Button menuButton; - public Button loginButton; - public Button chatButton; - public Button logoutButton; - public Button viewUserButton; - public Button helpButton; - -// // @TargetApi(Build.VERSION_CODES.KITKAT) -//// @SuppressLint("NewApi") -// public static String getFilePathFromURI(Context context, Uri uri) { -// // DocumentProvider -// if (DocumentsContract.isDocumentUri(context, uri)) { -// -// // ExternalStorageProvider -// if (isExternalStorageDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// -// if ("primary".equalsIgnoreCase(type)) { -// return Environment.getExternalStorageDirectory() + "/" + split[1]; -// } -// // TODO handle non-primary volumes -// } -// // DownloadsProvider -// else if (isDownloadsDocument(uri)) { -// final String id = DocumentsContract.getDocumentId(uri); -// final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), -// Long.valueOf(id)); -// return getDataColumn(context, contentUri, null, null); -// } -// // MediaProvider -// else if (isMediaDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// Uri contentUri = null; -// if ("image".equals(type)) { -// contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; -// } else if ("video".equals(type)) { -// contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; -// -// } else if ("audio".equals(type)) { -// contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; -// } -// final String selection = "_id=?"; -// final String[] selectionArgs = new String[]{split[1]}; -// return getDataColumn(context, contentUri, selection, selectionArgs); -// } -// } -// // MediaStore (and general) -// else if ("content".equalsIgnoreCase(uri.getScheme())) { -// // Return the remote address -// if (isGooglePhotosUri(uri)) -// return uri.getLastPathSegment(); -// return getDataColumn(context, uri, null, null); -// } -// // File -// else if ("file".equalsIgnoreCase(uri.getScheme())) { -// return uri.getPath(); -// } -// return null; -// } - - public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { -// Cursor cursor = null; -// final String column = "_data"; -// final String[] projection = {column}; -// try { -// cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); -// if (cursor != null && cursor.moveToFirst()) { -// final int index = cursor.getColumnIndexOrThrow(column); -// return cursor.getString(index); -// } -// } finally { -// if (cursor != null) -// cursor.close(); -// } - return null; - } + private static int templateID; + private Button spin; + private Button createInstanceButton; + private Button browseButton; + private Button menuButton; + private Button loginButton; + private Button chatButton; + private Button logoutButton; + private Button viewUserButton; + private Button helpButton; + /** + * getFileSize + * + * @param q + * @param a + * @return dd + */ public static Boolean getFileSize(String q, Context a) { if (q == null || q.equals("")) { return true; @@ -436,32 +260,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } - public static boolean isTablet(Context context) { -// return (context.getResourceManager().getConfiguration().isLayoutRTL -// & Configuration.AUTO_MODE) >= Configuration.AUTO_MODE; - return true; - } - - @SuppressWarnings("rawtypes") - public static Class getAbility(WebMediumConfig config) { - if (config instanceof ChannelConfig) { -// return ChannelAbility.class; //==================== - } else if (config instanceof ForumConfig) { -// return ForumAbility.class; //==================== - } else if (config instanceof InstanceConfig) { -// return BotAbility.class; //==================== - } else if (config instanceof DomainConfig) { -// return DomainAbility.class; //==================== - } else if (config instanceof AvatarConfig) { -// return AvatarAbility.class; //==================== - } else if (config instanceof ScriptConfig) { -// return ScriptAbility.class; //==================== - } else if (config instanceof GraphicConfig) { -// return GraphicAbility.class; //==================== - } - return null; - } - + /** + * error + * + * @param message + * @param exception + * @param ability + */ public static void error(String message, Exception exception, Ability ability) { try { if (DEBUG) { @@ -482,6 +287,14 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * errorInfo + * + * @param type + * @param message + * @param exception + * @param ability + */ public static void errorInfo(int type, String message, Exception exception, Ability ability) { try { if (DEBUG) { @@ -502,6 +315,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * showMessage + * + * @param title + * @param message + * @param ability + */ public static void showMessage(String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -531,6 +351,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * showLogin + * + * @param title + * @param message + * @param ability + */ public void showLogin(String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -561,8 +388,16 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } - public static Text execcontentinfo; + private static Text execcontentinfo; + /** + * showMessageInfo + * + * @param type + * @param title + * @param message + * @param ability + */ public static void showMessageInfo(int type, String title, String message, Ability ability) { CommonDialog mCommonDialog = new CommonDialog(ability); Optional @@ -598,70 +433,19 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * showMessage + * + * @param message + * @param ability + */ public static void showMessage(String message, Ability ability) { showMessage(null, message, ability); } - public static void prompt(String message, Ability ability, TextField text, IDialog.ClickedListener listener) { - CommonDialog dialog = new CommonDialog(ability); - dialog.setContentText(message); - dialog.setContentCustomComponent(text); - dialog.setButton(0, "OK", listener); - dialog.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - - } - }); - dialog.show(); - } - - public void contentRatingList() { - CommonDialog builder = new CommonDialog(this); - builder.setTitleText("Content Rating"); - builder.setContentText("Select Content Rating: "); - builder.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int id) { - - } - }); - - builder.setButton(1, "Cancel", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - - } - }); - builder.show(); - } - - public static void confirm(String message, Ability ability, Boolean cancelable, IDialog.ClickedListener listener) { - CommonDialog dialog = new CommonDialog(ability); - dialog.setTitleText("Pizza Bot"); - dialog.setContentText(message); - dialog.setButton(0, "Yes", listener); - dialog.setButton(1, "NO", listener); - if (cancelable) { - dialog.setButton(1, "Cancel", listener); - } - dialog.show(); - } - - public static List getAllTemplates(Ability ability) { - if (templates == null) { - try { - HttpGetTemplatesAction action = new HttpGetTemplatesAction(ability); - action.postExecute(action.execute().get()); - if (action.getException() != null) { - templates = new ArrayList(); - } - } catch (Exception ignore) { - } - } - return templates; - } - + /** + * REQ_PERMISSION_CODE + */ public static final int REQ_PERMISSION_CODE = 1003; private final List mPermissions = new LinkedList<>( @@ -671,57 +455,39 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag @Override public void onStart(Intent intent) { super.onStart(intent); -// super.setMainRoute(MainAbilitySlice.class.getName()); - searching = false; - browsing = false; - searchingPosts = false; - importingBotLog = false; - importingBotScript = false; + setSearching(false); + setBrowsing(false); + setSearchingPosts(false); + setImportingBotLog(false); + setImportingBotScript(false); if (user != null) { Preferences cookies = PreferencesUtils.getPreferences(this); cookies.putString("user", MainAbility.user.user); cookies.putString("token", MainAbility.user.token); cookies.flushSync(); } - - current = this; + setCurrent(this); Preferences cookies = PreferencesUtils.getPreferences(this); // saved handsFreeSpeech toggle - load cookies. - handsFreeSpeech = cookies.getBoolean("handsfreespeech", handsFreeSpeech); - listenInBackground = cookies.getBoolean("listenInBackground", listenInBackground); - offlineSpeech = cookies.getBoolean("offlineSpeech", offlineSpeech); -// ChatAbility.DEBUG = cookies.getBoolean("debug", ChatAbility.DEBUG); //=============================================== - launchInstanceId = cookies.getString("instanceID", launchInstanceId); - launchInstanceName = cookies.getString("instanceName", launchInstanceName); + setHandsFreeSpeech(cookies.getBoolean("handsfreespeech", handsFreeSpeech)); + setListenInBackground(cookies.getBoolean("listenInBackground", listenInBackground)); + setOfflineSpeech(cookies.getBoolean("offlineSpeech", offlineSpeech)); + setLaunchInstanceId(cookies.getString("instanceID", launchInstanceId)); + setLaunchInstanceName(cookies.getString("instanceName", launchInstanceName)); // saving the a number of array as an ID, for the sake of loading the // exact saved bot. - templateID = cookies.getInt("tempId", templateID); - nameOfAvatar = cookies.getString("nameOfAvatar", nameOfAvatar); - System.out.println("Name of avatar: " + nameOfAvatar); - // load memory: by bot's name - + setTemplateID(cookies.getInt("tempId", templateID)); + setNameOfAvatar(cookies.getString("nameOfAvatar", nameOfAvatar)); loadMemoryByBot(); // Checking and making sure that the mic is turned off to start // configuring the microphone. - micConfig = cookies.getBoolean("miconfig", micConfig); + setMicConfig(cookies.getBoolean("miconfig", micConfig)); if (user == null) { String user = cookies.getString("user", null); String token = cookies.getString("token", null); - // Check Volume - AudioManager audioManager = new AudioManager(this); - int volume = 0; - try { - volume = audioManager.getVolume(AudioManager.AudioVolumeType.STREAM_MUSIC); - } catch (AudioRemoteException e) { - e.printStackTrace(); - } - if (volume == 0 || volume < 1) { -// Toast.makeText(this, "Please check 'Media' volume", Toast.LENGTH_LONG).show(); - } - if ((user != null) && (token != null)) { UserConfig config = new UserConfig(); config.user = user; @@ -734,20 +500,20 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag String nativeVoice = cookies.getString("nativeVoice", null); if (voice != null) { - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); + setCustomVoice(true); + setVoice(new VoiceConfig()); MainAbility.voice.voice = voice; MainAbility.voice.language = language; MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setDeviceVoice(MainAbility.voice.nativeVoice); } if (translate != null) { - MainAbility.translate = true; - MainAbility.customVoice = true; - MainAbility.voice = new VoiceConfig(); + setTranslate(true); + setCustomVoice(true); + setVoice(new VoiceConfig()); MainAbility.voice.language = language; MainAbility.voice.nativeVoice = Boolean.valueOf(nativeVoice); - MainAbility.deviceVoice = MainAbility.voice.nativeVoice; + setDeviceVoice(MainAbility.voice.nativeVoice); } } @@ -763,10 +529,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } resetView(); - searching = false; - hd = isTablet(this); + setSearching(false); + setHd(true); } + /** + * initChat + */ public void initChat() { chatButton = (Button) findComponentById(ResourceTable.Id_chatButton); // chat chatButton.setClickedListener(new Component.ClickedListener() { @@ -785,6 +554,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * initMain + */ public void initMain() { spin = (Button) findComponentById(ResourceTable.Id_selectButton); // 底部类型选择 spin.setClickedListener(new Component.ClickedListener() { @@ -846,6 +618,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * initBrowse + */ public void initBrowse() { chatButton = (Button) findComponentById(ResourceTable.Id_chatButton); chatButton.setClickedListener(new Component.ClickedListener() { @@ -916,20 +691,22 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * loadMemoryByBot + */ public void loadMemoryByBot() { - MicroMemory.storageDir = getFilesDir(); - List items = new ArrayList(); - items = ListTemplateView.retriveTemplates(); + List items = ListTemplateView.retriveTemplates(); OfflineTemplateConfig oneItem; oneItem = items.get(templateID); System.out.println("StorageFileName :" + oneItem.getTitle()); - offlineSelectedImage = oneItem.getImageId(); - MicroMemory.storageFileName = oneItem.getTitle(); - launchInstanceName = oneItem.getTitle(); - launchInstanceId = oneItem.getId(); + setOfflineSelectedImage(oneItem.getImageId()); + setLaunchInstanceName(oneItem.getTitle()); + setLaunchInstanceId(oneItem.getId()); } - @SuppressWarnings({"unchecked", "rawtypes"}) + /** + * resetView + */ public void resetView() { menuButton = (Button) findComponentById(ResourceTable.Id_menuButton); // 菜单选择 menuButton.setClickedListener(new Component.ClickedListener() { @@ -944,15 +721,15 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag resetLast(); } + /** + * resetLast + */ public void resetLast() { if (type.equals("Chat Bot Wars")) { war(); return; } - if (type == null) { - type = MainAbility.defaultType; - } Button button = (Button) findComponentById(ResourceTable.Id_lastButton); if (button != null) { Preferences cookies = PreferencesUtils.getPreferences(this); @@ -983,12 +760,10 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } + /** + * openLast + */ public void openLast() { - -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); // 适配器中做了选择赋值 -// if (spin != null) { -// type = (String) spin.getSelectedItem(); -// } if (type == null) { type = MainAbility.defaultType; } @@ -1034,6 +809,11 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag config.name = last; } + /** + * resetMenu + * + * @param menu + */ public void resetMenu(Menu menu) { if (menu == null) { return; @@ -1041,79 +821,44 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag for (int index = 0; index < menu.getItemCount(); index++) { menu.getItem(index).setEnabled(true); } - if (MainAbility.user == null) { - //menu.findItem(R.id.menuMyBots).setEnabled(false); - //menu.findItem(R.id.menuSignOut).setEnabled(false); - //menu.findItem(R.id.menuViewUser).setEnabled(false); - //menu.findItem(R.id.menuEditUser).setEnabled(false); - } else { - //menu.findItem(R.id.menuSignIn).setEnabled(false); - //menu.findItem(R.id.menuSignUp).setEnabled(false); - } - - /*if (MicroMemory.checkExists()) { - menu.findItem(R.id.menuDeleteExistingBot).setEnabled(true); - } else { - menu.findItem(R.id.menuDeleteExistingBot).setEnabled(false); - }*/ - -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String) spin.getSelectedItem(); -// } if (type == null) { type = MainAbility.defaultType; } - // MenuItem item = menu.findItem(R.id.menuMyBots); - // if (type.equals("Bots")) { - // item.setTitle("My Bots"); - // } else if (type.equals("Forums")) { - // item.setTitle("My Forums"); - // } else if (type.equals("Live Chat")) { - // item.setTitle("My Channels"); - // } else if (type.equals("Domains")) { - // item.setTitle("My Domains"); - // } else if (type.equals("Avatars")) { - // item.setTitle("My Avatars"); - // } else if (type.equals("Scripts")){ - // item.setTitle("My Scripts"); - // }else if (type.equals("Graphics")){ - // item.setTitle("My Graphics"); - // } + } + /** + * war + */ public void war() { startOpenAbility(this, StartWarAbility.class.getName()); } + /** + * login + */ public void login() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } - startOpenAbility(this, LoginAbility.class.getName()); } + /** + * logout + */ public void logout() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } connection.disconnect(); - user = null; - instance = null; - conversation = null; - post = null; - posts = new ArrayList(); - instances = new ArrayList(); - domain = null; - tags = null; - categories = null; - learning = null; - voice = null; - customVoice = false; - translate = false; + setUser(null); + setInstance(null); + setConversation(null); + setPost(null); + setPosts(new ArrayList()); + setInstances(new ArrayList()); + setDomain(null); + setTags(null); + setCategories(null); + setLearning(null); + setVoice(null); + setCustomVoice(false); + setTranslate(false); Preferences editor = PreferencesUtils.getPreferences(this); editor.delete("user"); @@ -1140,6 +885,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag startAbility(intent); } + /** + * menu + */ public void menu() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); @@ -1194,7 +942,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag editprofile.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - editUser(); } }); @@ -1250,15 +997,19 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + /** + * createUser + */ public void createUser() { startOpenAbility(this, CreateUserAbility.class.getName()); } - public void editUser() { - - } - + /** + * setOnline + * + * @param result + */ public static void setOnline(boolean result) { if (result) { connection = remoteConnection; @@ -1268,16 +1019,24 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag online = result; } + /** + * help + */ public void help() { - startOpenAbility(this, HelpAbility.class.getName()); } + /** + * viewUser + */ public void viewUser() { - viewUser = user; + setViewUser(user); } + /** + * openWebsite + */ public void openWebsite() { try { Intent intent2 = new Intent(); @@ -1291,6 +1050,9 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } + /** + * createInstance + */ public void createInstance() { if (user == null) { showLogin("", "You must sign in first", this); @@ -1300,10 +1062,13 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag type = MainAbility.defaultType; } if (type.equals("Bots")) { - MainAbility.template = ""; + setTemplate(""); } } + /** + * search + */ public void search() { if (type == null) { type = MainAbility.defaultType; @@ -1313,37 +1078,10 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } } - public void browseMyBots() { - if (type == null) { - type = MainAbility.defaultType; - } - BrowseConfig config = new BrowseConfig(); - config.typeFilter = "Personal"; - if (type.equals("Bots")) { - config.type = "Bot"; - } else if (type.equals("Forums")) { - config.type = "Forum"; - } else if (type.equals("Live Chat")) { - config.type = "Channel"; - } else if (type.equals("Domains")) { - config.type = "Domain"; - } else if (type.equals("Avatars")) { - config.type = "Avatar"; - } else if (type.equals("Scripts")) { - config.type = "Script"; - } else if (type.equals("Graphics")) { - config.type = "Graphic"; - } - config.contentRating = "Mature"; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); - } - + /** + * browse + */ public void browse() { -// Spinner spin = (Spinner) findViewById(R.id.typeSpin); -// if (spin != null) { -// type = (String)spin.getSelectedItem(); -// } if (type == null) { type = MainAbility.defaultType; } @@ -1359,14 +1097,12 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } else if (type.equals("Avatars")) { config.type = "Avatar"; } else if (type.equals("Scripts")) { - importingBotScript = false; + setImportingBotScript(false); config.type = "Script"; } else if (type.equals("Graphics")) { config.type = "Graphic"; } config.contentRating = MainAbility.contentRating; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); } /** @@ -1388,12 +1124,6 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag /** * Start a chat session with the hard coded instance. */ - - /* - * This method will have a list of 8 empty bot, basic, AI, julie, eddie, - * alice, personal assistance, juile assistance. before attaching the ID and - * Name of the bot make sure that its selecetd thro the list. - */ public void launch() { WebMediumConfig config = null; if (launchType == LaunchType.Bot) { @@ -1408,40 +1138,15 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag } - public void saveAllData(String instanceId, String instanceName, int id) { -// Preferences cookies = MainAbility.current.getPreferences(Context.MODE_PRIVATE).edit(); - Preferences cookies = PreferencesUtils.getPreferences(this); - cookies.putString("instanceID", instanceId); - cookies.putString("instanceName", instanceName); - cookies.putInt("tempId", id); - cookies.flushSync(); - } + private static String selectInfo = ""; + Text languageselect; /** - * View the user's personal instance. + * changeLanguage + * + * @param activty + * @param listener */ - public void browseMyBot() { - if (user == null) { - CommonDialog dialog = new CommonDialog(this); - dialog.setContentText("You must sign in first"); - dialog.setButton(1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - login(); - } - }); - dialog.show(); - return; - } - WebMediumConfig config = new InstanceConfig(); - config.name = "Bot " + MainAbility.user.user; - - } - - public static String selectInfo = ""; - Text languageselect; - - @SuppressWarnings({"rawtypes", "unchecked"}) public void changeLanguage(Ability activty, final IDialog.ClickedListener listener) { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); @@ -1469,29 +1174,20 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag LanguageDialogBuilder.with(MainAbility.this).setSelectLanguageInterface(MainAbility.this); } }); - - int index = -1; - - if (MainAbility.voice != null && MainAbility.voice.language != null) { - index = Arrays.asList(MainAbility.languages).indexOf(MainAbility.voice.language); - } -// spin.setSelection(index); languageselect.setText(MainAbility.languages[0] + ""); if (MainAbility.voice != null && MainAbility.voice.language != null) { for (int i = 0; i < spinnerAdapter.getCount(); i++) { if (MainAbility.languages[i].contains(MainAbility.voice.language + " - ")) { -// spin.setSelection(i); languageselect.setText(MainAbility.languages[i] + ""); } } } -// dialog.setView(spin); ok.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { // String lang = (String)spin.getSelectedItem(); - String lang = MainAbility.selectInfo; + String lang = MainAbility.getSelectInfo(); if (lang.equals("Default")) { MainAbility.translate = false; MainAbility.customVoice = false; @@ -1535,4 +1231,822 @@ public class MainAbility extends LibreAbility implements SelectListener, Languag }); } + public static boolean isDEBUG() { + return DEBUG; + } + + public static String getApplicationId() { + return applicationId; + } + + public static void setApplicationId(String applicationId) { + MainAbility.applicationId = applicationId; + } + + public static SDKConnection getConnection() { + return connection; + } + + public static void setConnection(SDKConnection connection) { + MainAbility.connection = connection; + } + + public static SDKConnection getLocalConnection() { + return localConnection; + } + + public static void setLocalConnection(SDKConnection localConnection) { + MainAbility.localConnection = localConnection; + } + + public static SDKConnection getRemoteConnection() { + return remoteConnection; + } + + public static void setRemoteConnection(SDKConnection remoteConnection) { + MainAbility.remoteConnection = remoteConnection; + } + + public static String getDomainId() { + return domainId; + } + + public static void setDomainId(String domainId) { + MainAbility.domainId = domainId; + } + + public static DomainConfig getDomain() { + return domain; + } + + public static void setDomain(DomainConfig domain) { + MainAbility.domain = domain; + } + + public static String getDefaultType() { + return defaultType; + } + + public static void setDefaultType(String defaultType) { + MainAbility.defaultType = defaultType; + } + + public static boolean isShowAds() { + return showAds; + } + + public static void setShowAds(boolean showAds) { + MainAbility.showAds = showAds; + } + + public static String getWEBSITEHTTPS() { + return WEBSITEHTTPS; + } + + public static String getLaunchInstanceId() { + return launchInstanceId; + } + + public static void setLaunchInstanceId(String launchInstanceId) { + MainAbility.launchInstanceId = launchInstanceId; + } + + public static String getLaunchInstanceName() { + return launchInstanceName; + } + + public static void setLaunchInstanceName(String launchInstanceName) { + MainAbility.launchInstanceName = launchInstanceName; + } + + public static String getWebsite() { + return website; + } + + public static void setWebsite(String website) { + MainAbility.website = website; + } + + public static LaunchType getLaunchType() { + return launchType; + } + + public static void setLaunchType(LaunchType launchType) { + MainAbility.launchType = launchType; + } + + public static boolean isOnline() { + return online; + } + + public static boolean isHandsFreeSpeech() { + return handsFreeSpeech; + } + + public static void setHandsFreeSpeech(boolean handsFreeSpeech) { + MainAbility.handsFreeSpeech = handsFreeSpeech; + } + + public static boolean isListenInBackground() { + return listenInBackground; + } + + public static void setListenInBackground(boolean listenInBackground) { + MainAbility.listenInBackground = listenInBackground; + } + + public static boolean isMicConfig() { + return micConfig; + } + + public static void setMicConfig(boolean micConfig) { + MainAbility.micConfig = micConfig; + } + + public static int getOfflineSelectedImage() { + return offlineSelectedImage; + } + + public static void setOfflineSelectedImage(int offlineSelectedImage) { + MainAbility.offlineSelectedImage = offlineSelectedImage; + } + + public static boolean isSound() { + return sound; + } + + public static void setSound(boolean sound) { + MainAbility.sound = sound; + } + + public static boolean isDisableVideo() { + return disableVideo; + } + + public static void setDisableVideo(boolean disableVideo) { + MainAbility.disableVideo = disableVideo; + } + + public static boolean isWebm() { + return webm; + } + + public static void setWebm(boolean webm) { + MainAbility.webm = webm; + } + + public static boolean isHd() { + return hd; + } + + public static void setHd(boolean hd) { + MainAbility.hd = hd; + } + + public static boolean isDeviceVoice() { + return deviceVoice; + } + + public static void setDeviceVoice(boolean deviceVoice) { + MainAbility.deviceVoice = deviceVoice; + } + + public static boolean isCustomVoice() { + return customVoice; + } + + public static void setCustomVoice(boolean customVoice) { + MainAbility.customVoice = customVoice; + } + + public static boolean isTranslate() { + return translate; + } + + public static void setTranslate(boolean translate) { + MainAbility.translate = translate; + } + + public static boolean isOfflineSpeech() { + return offlineSpeech; + } + + public static void setOfflineSpeech(boolean offlineSpeech) { + MainAbility.offlineSpeech = offlineSpeech; + } + + public static WebMediumConfig getInstance() { + return instance; + } + + public static void setInstance(WebMediumConfig instance) { + MainAbility.instance = instance; + } + + public static ForumPostConfig getPost() { + return post; + } + + public static void setPost(ForumPostConfig post) { + MainAbility.post = post; + } + + public static IssueConfig getIssue() { + return issue; + } + + public static void setIssue(IssueConfig issue) { + MainAbility.issue = issue; + } + + public static UserConfig getUser() { + return user; + } + + /** + * setUser + * + * @param user + */ + public static void setUser(UserConfig user) { + if (user != null) { + MainAbility.user = user; + + } + } + + public static UserConfig getViewUser() { + return viewUser; + } + + public static void setViewUser(UserConfig viewUser) { + MainAbility.viewUser = viewUser; + } + + public static String getType() { + return type; + } + + public static void setType(String type) { + MainAbility.type = type; + } + + public static VoiceConfig getVoice() { + return voice; + } + + public static void setVoice(VoiceConfig voice) { + MainAbility.voice = voice; + } + + public static LearningConfig getLearning() { + return learning; + } + + public static void setLearning(LearningConfig learning) { + MainAbility.learning = learning; + } + + public static ResponseConfig getResponse() { + return response; + } + + public static void setResponse(ResponseConfig response) { + MainAbility.response = response; + } + + public static ScriptSourceConfig getScript() { + return script; + } + + public static void setScript(ScriptSourceConfig script) { + MainAbility.script = script; + } + + public static String getConversation() { + return conversation; + } + + public static void setConversation(String conversation) { + MainAbility.conversation = conversation; + } + + public static String getTemplate() { + return template; + } + + public static void setTemplate(String template) { + MainAbility.template = template; + } + + public static List getTemplates() { + return templates; + } + + public static void setTemplates(List templates) { + MainAbility.templates = templates; + } + + /** + * getTags + * + * @return dd + */ + public static Object[] getTags() { + return tags.clone(); + } + + /** + * setTags + * + * @param tag + */ + public static void setTags(Object[] tag) { + if (tag != null) { + tags = tag.clone(); + } + } + + /** + * getCategories + * + * @return dd + */ + public static Object[] getCategories() { + return categories.clone(); + } + + /** + * setCategories + * + * @param categorie + */ + public static void setCategories(Object[] categorie) { + if (categorie != null) { + categories = categorie.clone(); + } + } + + /** + * getChannelTags + * + * @return dd + */ + public static Object[] getChannelTags() { + return channelTags.clone(); + } + + /** + * setChannelTags + * + * @param channelTag + */ + public static void setChannelTags(Object[] channelTag) { + channelTags = channelTag.clone(); + } + + /** + * getVolume + * + * @return dd + */ + public static int getVolume() { + return volume; + } + + /** + * setVolume + * + * @param volume + */ + public static void setVolume(int volume) { + MainAbility.volume = volume; + } + + /** + * getContentRating + * + * @return dd + */ + public static String getContentRating() { + return contentRating; + } + + /** + * setContentRating + * + * @param contentRating + */ + public static void setContentRating(String contentRating) { + MainAbility.contentRating = contentRating; + } + + /** + * getNameOfAvatar + * + * @return dd + */ + public static String getNameOfAvatar() { + return nameOfAvatar; + } + + /** + * setNameOfAvatar + * + * @param nameOfAvatar + */ + public static void setNameOfAvatar(String nameOfAvatar) { + MainAbility.nameOfAvatar = nameOfAvatar; + } + + /** + * isShowImages + * + * @return dd + */ + public static boolean isShowImages() { + return showImages; + } + + /** + * setShowImages + * + * @param showImages + */ + public static void setShowImages(boolean showImages) { + MainAbility.showImages = showImages; + } + + /** + * getInstances + * + * @return dd + */ + public static List getInstances() { + return instances; + } + + /** + * setInstances + * + * @param instances + */ + public static void setInstances(List instances) { + MainAbility.instances = instances; + } + + /** + * getPosts + * + * @return dd + */ + public static List getPosts() { + return posts; + } + + /** + * setPosts + * + * @param posts + */ + public static void setPosts(List posts) { + MainAbility.posts = posts; + } + + /** + * getCurrent + * + * @return dd + */ + public static MainAbility getCurrent() { + return current; + } + + /** + * setCurrent + * + * @param current + */ + public static void setCurrent(MainAbility current) { + MainAbility.current = current; + } + + /** + * isBrowsing + * + * @return dd + */ + public static boolean isBrowsing() { + return browsing; + } + + /** + * setBrowsing + * + * @param browsing + */ + public static void setBrowsing(boolean browsing) { + MainAbility.browsing = browsing; + } + + /** + * isSearching + * + * @return dd + */ + public static boolean isSearching() { + return searching; + } + + /** + * setSearching + * + * @param searching + */ + public static void setSearching(boolean searching) { + MainAbility.searching = searching; + } + + /** + * isSearchingPosts + * + * @return dd + */ + public static boolean isSearchingPosts() { + return searchingPosts; + } + + /** + * setSearchingPosts + * + * @param searchingPosts + */ + public static void setSearchingPosts(boolean searchingPosts) { + MainAbility.searchingPosts = searchingPosts; + } + + /** + * isImportingBotScript + * + * @return dd + */ + public static boolean isImportingBotScript() { + return importingBotScript; + } + + /** + * setImportingBotScript + * + * @param importingBotScript + */ + public static void setImportingBotScript(boolean importingBotScript) { + MainAbility.importingBotScript = importingBotScript; + } + + /** + * isImportingBotLog + * + * @return dd + */ + public static boolean isImportingBotLog() { + return importingBotLog; + } + + /** + * setImportingBotLog + * + * @param importingBotLog + */ + public static void setImportingBotLog(boolean importingBotLog) { + MainAbility.importingBotLog = importingBotLog; + } + + /** + * getLanguages + * + * @return dd + */ + public static String[] getLanguages() { + return languages.clone(); + } + + /** + * setLanguages + * + * @param language + */ + public static void setLanguages(String[] language) { + languages = language.clone(); + } + + /** + * getServers + * + * @return dd + */ + public static String[] getServers() { + return servers.clone(); + } + + /** + * setServers + * + * @param server + */ + public static void setServers(String[] server) { + servers = server.clone(); + } + + /** + * getTypes + * + * @return dd + */ + public static String[] getTypes() { + return types.clone(); + } + + /** + * setTypes + * + * @param type + */ + public static void setTypes(String[] type) { + types = type.clone(); + } + + /** + * getContentRatings + * + * @return dd + */ + public static String[] getContentRatings() { + return contentRatings.clone(); + } + + /** + * setContentRatings + * + * @param contentRating + */ + public static void setContentRatings(String[] contentRating) { + contentRatings = contentRating.clone(); + } + + /** + * getInputTypes + * + * @return dd + */ + public static String[] getInputTypes() { + return inputTypes.clone(); + } + + /** + * setInputTypes + * + * @param inputType + */ + public static void setInputTypes(String[] inputType) { + inputTypes = inputType.clone(); + } + + /** + * getMenu + * + * @return dd + */ + public Menu getMenu() { + return menu; + } + + /** + * setMenu + * + * @param menu + */ + public void setMenu(Menu menu) { + this.menu = menu; + } + + /** + * getTemplateID + * + * @return dd + */ + public static int getTemplateID() { + return templateID; + } + + /** + * setTemplateID + * + * @param templateID + */ + public static void setTemplateID(int templateID) { + MainAbility.templateID = templateID; + } + + /** + * getSpin + * + * @return dd + */ + public Button getSpin() { + return spin; + } + + /** + * setSpin + * + * @param spin + */ + public void setSpin(Button spin) { + this.spin = spin; + } + + /** + * getCreateInstanceButton + * + * @return dd + */ + public Button getCreateInstanceButton() { + return createInstanceButton; + } + + /** + * setCreateInstanceButton + * + * @param createInstanceButton + */ + public void setCreateInstanceButton(Button createInstanceButton) { + this.createInstanceButton = createInstanceButton; + } + + /** + * getBrowseButton + * + * @return dd + */ + public Button getBrowseButton() { + return browseButton; + } + + /** + * setBrowseButton + * + * @param browseButton + */ + public void setBrowseButton(Button browseButton) { + this.browseButton = browseButton; + } + + /** + * getReqPermissionCode + * @return dd + */ + public static int getReqPermissionCode() { + return REQ_PERMISSION_CODE; + } + + /** + * getmPermissions + * + * @return dd + */ + public List getmPermissions() { + return mPermissions; + } + + /** + * getSelectInfo + * @return dd + */ + public static String getSelectInfo() { + return selectInfo; + } + + /** + * setSelectInfo + * @param selectInfo + */ + public static void setSelectInfo(String selectInfo) { + MainAbility.selectInfo = selectInfo; + } + + /** + * getLanguageselect + * @return dd + */ + public Text getLanguageselect() { + return languageselect; + } + + /** + * setLanguageselect + * @param languageselect + */ + public void setLanguageselect(Text languageselect) { + this.languageselect = languageselect; + } } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/SDKConnection.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/SDKConnection.java index 7e5e0335e87858be02a220ab66dfb0f3108705de..6f4980b6f4d66cba3189571c6c548675078c1af9 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/SDKConnection.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/SDKConnection.java @@ -106,14 +106,9 @@ import javax.xml.parsers.DocumentBuilderFactory; * */ public class SDKConnection { - protected static String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; - protected static String[] channelTypes = new String[]{"ChatRoom", "OneOnOne"}; - protected static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; - protected static String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; - protected static String[] learningModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] correctionModes = new String[]{"Disabled", "Administrators", "Users", "Everyone"}; - protected static String[] botModes = new String[]{"ListenOnly", "AnswerOnly", "AnswerAndListen"}; - protected static String[] priorities = new String[]{"Low", "Medium", "High", "Sever"}; + private static String[] types = new String[]{"Bots", "Forums", "Graphics", "Live Chat", "Domains", "Scripts", "IssueTracker"}; + private static String[] accessModes = new String[]{"Everyone", "Users", "Members", "Administrators"}; + private static String[] mediaAccessModes = new String[]{"Everyone", "Users", "Members", "Administrators", "Disabled"}; protected String url; protected UserConfig user; @@ -162,10 +157,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-user", config.toXML()); Element root = parse(xml); - if (root == null) { - this.user = null; - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -189,9 +180,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/" + api, config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { result.parseXML(root); } catch (Exception exception) { @@ -233,9 +221,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/view-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -261,52 +246,6 @@ public class SDKConnection { } } - /** - * Fetch the forum post details for the forum post id. - * - * @param config ForumPostConfig - * @return ForumPostConfig - */ - public ForumPostConfig fetch(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-forum-post", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ForumPostConfig post = new ForumPostConfig(); - post.parseXML(root); - return post; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Fetch the issue details for the issue id. - * - * @param config IssueConfig - * @return IssueConfig - */ - public IssueConfig fetch(IssueConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/check-issue", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - IssueConfig issue = new IssueConfig(); - issue.parseXML(root); - return issue; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Create a new user. * @@ -318,9 +257,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POSTUpdate(ability, this.url + "/create-user", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { UserConfig user = new UserConfig(); user.parseXML(root); @@ -343,9 +279,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-forum-post", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ForumPostConfig post = new ForumPostConfig(); post.parseXML(root); @@ -367,9 +300,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-issue", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { IssueConfig issue = new IssueConfig(); issue.parseXML(root); @@ -379,163 +309,6 @@ public class SDKConnection { throw this.exception; } } - - /** - * Create a new file/image/media attachment for a chat channel. - * - * @param config MediaConfig - * @param file String - * @return MediaConfig - */ - public MediaConfig createChannelFileAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTFILE(this.url + "/create-channel-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for a chat channel. - * - * @param file String - * @param config MediaConfig - * @return MediaConfig - */ - public MediaConfig createChannelImageAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-channel-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new file/image/media attachment for an issue tracker. - * - * @param config MediaConfig - * @param file String - * @return MediaConfig - */ - public MediaConfig createIssueTrackerFileAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTFILE(this.url + "/create-issuetracker-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for an issue tracker. - * - * @param file String - * @param config MediaConfig - * @return MediaConfig - */ - public MediaConfig createIssueTrackerImageAttachment(String file, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-issuetracker-attachment", file, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a new image attachment for an issue tracker. - * - * @param config MediaConfig - * @param bitmap PixelMap - * @return MediaConfig - */ - public MediaConfig createIssueTrackerImageAttachment(PixelMap bitmap, MediaConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/create-issuetracker-attachment", bitmap, config.name, config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - MediaConfig media = new MediaConfig(); - media.parseXML(root); - return media; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a reply to a forum post. - * You must set the parent id for the post replying to. - * - * @param config ForumPostConfig - * @return ForumPostConfig - */ - public ForumPostConfig createReply(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/create-reply", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ForumPostConfig reply = new ForumPostConfig(); - reply.parseXML(root); - return reply; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create a user message. - * This can be used to send a user a direct message. - * SPAM will cause your account to be deleted. - * - * @param config UserMessageConfig - */ - public void createUserMessage(UserMessageConfig config) { - config.addCredentials(this); - POST(this.url + "/create-user-message", config.toXML()); - } - /** * Fetch the content details from the server. * The id or name and domain of the object must be set. @@ -548,9 +321,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/check-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -573,9 +343,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/create-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -597,9 +364,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/update-" + config.getType(), config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { config = (T) config.getClass().newInstance(); config.parseXML(root); @@ -609,102 +373,6 @@ public class SDKConnection { throw this.exception; } } - - /** - * Update the forum post. - * - * @param config ForumPostConfig - * @return ForumPostConfig - */ - public ForumPostConfig update(ForumPostConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-forum-post", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new ForumPostConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the issue. - * - * @param config IssueConfig - * @return IssueConfig - */ - public IssueConfig update(IssueConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-issue", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new IssueConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create or update the response. - * This can also be used to flag, unflag, validate, or invalidate a response. - * - * @param config ResponseConfig - * @return ResponseConfig - */ - public ResponseConfig saveResponse(ResponseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/save-response", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ResponseConfig response = new ResponseConfig(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the user details. - * The password must be passed to allow the update. - * - * @param config UserConfig - * @return UserConfig - */ - public UserConfig update(UserConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/update-user", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - UserConfig user = new UserConfig(); - user.parseXML(root); - this.user = user; - return user; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Permanently delete the content with the id. * @@ -980,9 +648,6 @@ public class SDKConnection { config.addCredentials(this); String xml = POST(this.url + "/post-chat", config.toXML()); Element root = parse(xml); - if (root == null) { - return null; - } try { ChatResponse response = new ChatResponse(); response.parseXML(root); @@ -992,398 +657,54 @@ public class SDKConnection { throw this.exception; } } - /** - * Process the avatar message and return the avatars response. - * This allows the speech and video animation for an avatar to be generated for the message. + * Return the list of bot templates. * - * @param config AvatarMessage - * @return ChatResponse + * @return list of bot templates */ - public ChatResponse avatarMessage(AvatarMessage config) { - config.addCredentials(this); - String xml = POST(this.url + "/avatar-message", config.toXML()); + public List getTemplates() { + String xml = GET(this.url + "/get-all-templates"); + List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return null; - } - try { - ChatResponse response = new ChatResponse(); - response.parseXML(root); - return response; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; + for (int index = 0; index < root.getChildNodes().getLength(); index++) { + InstanceConfig instance = new InstanceConfig(); + instance.parseXML((Element) root.getChildNodes().item(index)); + instances.add(instance); } + return instances; } - /** - * Process the speech message and return the server generate text-to-speech audio file. - * This allows for server-side speech generation. + * Save the image as the avatar's background. * - * @param config Speech - * @return String + * @param config AvatarMedia + * @param file String */ - public String tts(Speech config) { + public void saveAvatarBackground(String file, AvatarMedia config) { config.addCredentials(this); - return POST(this.url + "/speak", config.toXML()); + POSTIMAGE(this.url + "/save-avatar-background", file, config.name, config.toXML()); } - /** - * Return the administrators of the content. + * Update the contents icon. + * The file will be uploaded to the server. * - * @param config WebMediumConfig - * @return List + * @param config config + * @param file String + * @return WebMediumConfig */ - public List getAdmins(WebMediumConfig config) { + @SuppressWarnings("unchecked") + public T updateIcon(String file, T config) { config.addCredentials(this); - String xml = POST(this.url + "/get-" + config.getType() + "-admins", config.toXML()); - List users = new ArrayList(); + String xml = POSTIMAGE(this.url + "/update-" + config.getType() + "-icon", file, "image.jpg", config.toXML()); Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - UserConfig user = new UserConfig(); - user.parseXML((Element) root.getChildNodes().item(index)); - users.add(user.user); + try { + config = (T) config.getClass().newInstance(); + config.parseXML(root); + return config; + } catch (Exception exception) { + this.exception = SDKException.parseFailure(exception); + throw this.exception; } - return users; } - - /** - * Return the list of user details for the comma separated values list of user ids. - * - * @param usersCSV String - * @return list of user ids - */ - public List getUsers(String usersCSV) { - UserConfig config = new UserConfig(); - config.user = usersCSV; - config.addCredentials(this); - String xml = POST(this.url + "/get-users", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - Element child = (Element) root.getChildNodes().item(index); - UserConfig userConfig = new UserConfig(); - userConfig.parseXML(child); - users.add(userConfig); - } - return users; - } - - /** - * Return the list of forum posts for the forum browse criteria. - * - * @param config BrowseConfig - * @return list of forum posts for the forum browse criteria - */ - public List getPosts(BrowseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-forum-posts", config.toXML()); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ForumPostConfig post = new ForumPostConfig(); - post.parseXML((Element) root.getChildNodes().item(index)); - instances.add(post); - } - return instances; - } - - /** - * Return the list of issues for the issue tracker browse criteria. - * - * @param config BrowseConfig - * @return list of issues for the issue tracker browse criteria - */ - public List getIssues(BrowseConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-issues", config.toXML()); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - IssueConfig issue = new IssueConfig(); - issue.parseXML((Element) root.getChildNodes().item(index)); - instances.add(issue); - } - return instances; - } - - /** - * Return the list of categories for the type, and domain. - * - * @param config ContentConfig - * @return list of categories for the type, and domain - */ - public List getCategories(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-categories", config.toXML()); - List categories = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return categories; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ContentConfig category = new ContentConfig(); - category.parseXML((Element) root.getChildNodes().item(index)); - categories.add(category); - } - return categories; - } - - /** - * Return the list of tags for the type, and domain. - * - * @param config ContentConfig - * @return list of tags for the type, and domain - */ - public List getTags(ContentConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-tags", config.toXML()); - List tags = new ArrayList(); - tags.add(""); - Element root = parse(xml); - if (root == null) { - return tags; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - tags.add(((Element) root.getChildNodes().item(index)).getAttribute("name")); - } - return tags; - } - - /** - * Return the list of bot templates. - * - * @return list of bot templates - */ - public List getTemplates() { - String xml = GET(this.url + "/get-all-templates"); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - InstanceConfig instance = new InstanceConfig(); - instance.parseXML((Element) root.getChildNodes().item(index)); - instances.add(instance); - } - return instances; - } - - /** - * Return the users for the content. - * - * @param config WebMediumConfig - * @return users for the content - */ - public List getUsers(WebMediumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-" + config.getType() + "-users", config.toXML()); - List users = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return users; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - UserConfig user = new UserConfig(); - user.parseXML((Element) root.getChildNodes().item(index)); - users.add(user.user); - } - return users; - } - - /** - * Return the channel's bot configuration. - * - * @param config ChannelConfig - * @return channel's bot configuration - */ - public BotModeConfig getChannelBotMode(ChannelConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-channel-bot-mode", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - BotModeConfig botMode = new BotModeConfig(); - botMode.parseXML(root); - return botMode; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Save the channel's bot configuration. - * - * @param config BotModeConfig - */ - public void saveChannelBotMode(BotModeConfig config) { - config.addCredentials(this); - POST(this.url + "/save-channel-bot-mode", config.toXML()); - } - - /** - * Save the forum's bot configuration. - * - * @param config BotModeConfig - */ - public void saveForumBotMode(BotModeConfig config) { - config.addCredentials(this); - POST(this.url + "/save-forum-bot-mode", config.toXML()); - } - - /** - * Save the bot's learning configuration. - * - * @param config LearningConfig - */ - public void saveLearning(LearningConfig config) { - config.addCredentials(this); - POST(this.url + "/save-learning", config.toXML()); - } - - /** - * Save the bot's voice configuration. - * - * @param config VoiceConfig - */ - public void saveVoice(VoiceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-voice", config.toXML()); - } - - /** - * Save the bot's avatar configuration. - * - * @param config InstanceConfig - */ - public void saveBotAvatar(InstanceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-bot-avatar", config.toXML()); - } - - /** - * Perform the user administration task (add or remove users, or administrators). - * - * @param config UserAdminConfig - */ - public void userAdmin(UserAdminConfig config) { - config.addCredentials(this); - POST(this.url + "/user-admin", config.toXML()); - } - - /** - * Save the image as the avatar's background. - * - * @param config AvatarMedia - * @param file String - */ - public void saveAvatarBackground(String file, AvatarMedia config) { - config.addCredentials(this); - POSTIMAGE(this.url + "/save-avatar-background", file, config.name, config.toXML()); - } - - /** - * Add the avatar media file to the avatar. - * - * @param config AvatarMedia - * @param file String - */ - public void createAvatarMedia(String file, AvatarMedia config) { - config.addCredentials(this); - if ((file.indexOf(".jpg") != -1) || (file.indexOf(".jpeg") != -1)) { - if (config.hd) { - POSTHDIMAGE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } else { - POSTIMAGE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } - } else { - POSTFILE(this.url + "/create-avatar-media", file, config.name, config.toXML()); - } - } - - /** - * Add the graphic media file to the graphic. - * - * @param config GraphicConfig - * @param file String - */ - public void createGraphicMedia(String file, GraphicConfig config) { - config.addCredentials(this); - if ((file.indexOf(".jpg") != -1) || (file.indexOf(".jpeg") != -1)) { - POSTIMAGE(this.url + "/update-graphic-media", file, config.fileName, config.toXML()); - } else { - POSTFILE(this.url + "/update-graphic-media", file, config.fileName, config.toXML()); - } - } - - /** - * Update the contents icon. - * The file will be uploaded to the server. - * - * @param config config - * @param file String - * @return WebMediumConfig - */ - @SuppressWarnings("unchecked") - public T updateIcon(String file, T config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-" + config.getType() + "-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = (T) config.getClass().newInstance(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Update the user's icon. - * The file will be uploaded to the server. - * - * @param file String - * @param config UserConfig - * @return UserConfig - */ - public UserConfig updateIcon(String file, UserConfig config) { - config.addCredentials(this); - String xml = POSTIMAGE(this.url + "/update-user-icon", file, "image.jpg", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - config = new UserConfig(); - config.parseXML(root); - return config; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * POSTIMAGE * @@ -1402,188 +723,6 @@ public class SDKConnection { String result = ""; return result; } - - /** - * POSTIMAGE - * - * @param xml String - * @param name String - * @param url String - * @param bitmap PixelMap - * @return String - */ - public String POSTIMAGE(String url, PixelMap bitmap, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("XML: " + xml); - } - String result = ""; - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - byte[] byte_arr = stream.toByteArray(); - ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); - - MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); - - multipartEntity.addPart("file", fileBody); - multipartEntity.addPart("xml", new StringBody(xml)); - - HttpClient httpclient = new DefaultHttpClient(); - HttpResponse response = null; - - HttpPost httppost = new HttpPost(url); - httppost.setEntity(multipartEntity); - response = httpclient.execute(httppost); - - HttpEntity entity = response.getEntity(); - if (entity != null) { - result = EntityUtils.toString(entity, HTTP.UTF_8); - } - - if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { - this.exception = new SDKException("" - + response.getStatusLine().getStatusCode() - + " : " + result); - throw this.exception; - } - - } catch (Exception exception) { - this.exception = new SDKException(exception); - throw this.exception; - } - return result; - } - - /** - * POSTHDIMAGE - * - * @param url String - * @param name String - * @param xml String - * @param file String - * @return String - */ - public String POSTHDIMAGE(String url, String file, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("file: " + file); - System.out.println("XML: " + xml); - } - String result = ""; - try { - } catch (Exception exception) { - this.exception = new SDKException(exception); - throw this.exception; - } - return result; - } - - /** - * POSTFILE - * - * @param xml String - * @param name String - * @param url String - * @param path String - * @return String - */ - public String POSTFILE(String url, String path, String name, String xml) { - if (this.debug) { - System.out.println("POST: " + url); - System.out.println("file: " + path); - System.out.println("XML: " + xml); - } - String result = ""; - try { - File file = new File(path); - FileInputStream stream = new FileInputStream(file); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - int read = 0; - byte[] buffer = new byte[4096]; - while ((read = stream.read(buffer)) != -1) { - output.write(buffer, 0, read); - } - byte[] byte_arr = output.toByteArray(); - stream.close(); - ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); - - MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); - - multipartEntity.addPart("file", fileBody); - multipartEntity.addPart("xml", new StringBody(xml)); - - HttpClient httpclient = new DefaultHttpClient(); - HttpResponse response = null; - - HttpPost httppost = new HttpPost(url); - httppost.setEntity(multipartEntity); - response = httpclient.execute(httppost); - - HttpEntity entity = response.getEntity(); - if (entity != null) { - result = EntityUtils.toString(entity, HTTP.UTF_8); - } - - if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { - this.exception = new SDKException("" - + response.getStatusLine().getStatusCode() - + " : " + result); - throw this.exception; - } - - } catch (Exception exception) { - this.exception = new SDKException(exception); - throw this.exception; - } - return result; - } - - /** - * Return the forum's bot configuration. - * - * @param config ForumConfig - * @return BotModeConfig - */ - public BotModeConfig getForumBotMode(ForumConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-forum-bot-mode", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - BotModeConfig botMode = new BotModeConfig(); - botMode.parseXML(root); - return botMode; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Return the bot's voice configuration. - * - * @param config InstanceConfig - * @return VoiceConfig - */ - public VoiceConfig getVoice(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-voice", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - VoiceConfig voice = new VoiceConfig(); - voice.parseXML(root); - return voice; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Return the bot's default responses. * @@ -1595,82 +734,12 @@ public class SDKConnection { String xml = POST(this.url + "/get-default-responses", config.toXML()); List defaultResponses = new ArrayList(); Element root = parse(xml); - if (root == null) { - return defaultResponses; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { defaultResponses.add(((Element) root.getChildNodes().item(index)).getChildNodes().item(0).getTextContent()); } return defaultResponses; } - /** - * Search the bot's responses. - * - * @param config ResponseSearchConfig - * @return bot's responses - */ - public List getResponses(ResponseSearchConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-responses", config.toXML()); - List responses = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return responses; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ResponseConfig response = new ResponseConfig(); - response.parseXML((Element) root.getChildNodes().item(index)); - responses.add(response); - } - return responses; - } - - /** - * Search the bot's conversations. - * - * @param config ResponseSearchConfig - * @return bot's conversations - */ - public List getConversations(ResponseSearchConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-conversations", config.toXML()); - List conversations = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return conversations; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - ConversationConfig response = new ConversationConfig(); - response.parseXML((Element) root.getChildNodes().item(index)); - conversations.add(response); - } - return conversations; - } - - /** - * Return the bot's learning configuration. - * - * @param config InstanceConfig - * @return bot's learning configuration - */ - public LearningConfig getLearning(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-learning", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - LearningConfig learning = new LearningConfig(); - learning.parseXML(root); - return learning; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - /** * Return the list of content for the browse criteria. * The type defines the content type (one of Bot, Forum, Channel, Domain). @@ -1690,9 +759,6 @@ public class SDKConnection { String xml = POSTUpdate(ability, this.url + type, config.toXML()); List instances = new ArrayList(); Element root = parse(xml); - if (root == null) { - return instances; - } for (int index = 0; index < root.getChildNodes().getLength(); index++) { WebMediumConfig instance = null; if (config.type.equals("Bot")) { @@ -1715,185 +781,13 @@ public class SDKConnection { } return instances; } - - /** - * Return the list of media for the avatar. - * - * @param config AvatarConfig - * @return list of media for the avatar - */ - public List getAvatarMedia(AvatarConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-avatar-media", config.toXML()); - List instances = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return instances; - } - for (int index = 0; index < root.getChildNodes().getLength(); index++) { - AvatarMedia instance = new AvatarMedia(); - instance.parseXML((Element) root.getChildNodes().item(index)); - instances.add(instance); - } - return instances; - } - - /** - * Return the script source - * - * @param config ScriptConfig - * @return script source - */ - public ScriptSourceConfig getScriptSource(ScriptConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-script-source", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ScriptSourceConfig script = new ScriptSourceConfig(); - script.parseXML(root); - return script; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Create or update script - Save the script source - * - * @param config ScriptSourceConfig - */ - public void saveScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-script-source", config.toXML()); - } - - /** - * Return the source code for a single bot script - * - * @param config ScriptSourceConfig - * @return ScriptSourceConfig - */ - public ScriptSourceConfig getBotScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-bot-script-source", config.toXML()); - Element root = parse(xml); - if (root == null) { - return null; - } - try { - ScriptSourceConfig botScript = new ScriptSourceConfig(); - botScript.parseXML(root); - return botScript; - } catch (Exception exception) { - this.exception = SDKException.parseFailure(exception); - throw this.exception; - } - } - - /** - * Return a list of the bots scripts - * - * @param config InstanceConfig - * @return list of the bots scripts - */ - public List getBotScripts(InstanceConfig config) { - config.addCredentials(this); - String xml = POST(this.url + "/get-bot-scripts", config.toXML()); - List botScripts = new ArrayList(); - Element root = parse(xml); - if (root == null) { - return botScripts; - } - for (int i = 0; i < root.getChildNodes().getLength(); i++) { - ScriptConfig script = new ScriptConfig(); - script.parseXML((Element) root.getChildNodes().item(i)); - botScripts.add(script); - } - return botScripts; - } - - /** - * import a script to the bot - * - * @param config ScriptConfig - */ - - public void importBotScript(ScriptConfig config) { - config.addCredentials(this); - POST(this.url + "/import-bot-script", config.toXML()); - } - - /** - * import a chatlog/response list to the bot - * - * @param config ScriptConfig - */ - public void importBotLog(ScriptConfig config) { - config.addCredentials(this); - POST(this.url + "/import-bot-log", config.toXML()); - } - - - /** - * Save the bot script source - * - * @param config ScriptSourceConfig - */ - public void saveBotScriptSource(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/save-bot-script-source", config.toXML()); - } - - /** - * Delete selected bot script - * - * @param config ScriptSourceConfig - */ - public void deleteBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/delete-bot-script", config.toXML()); - } - - /** - * Move up one bot script - * - * @param config ScriptSourceConfig - */ - public void upBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/up-bot-script", config.toXML()); - } - - /** - * Move down one bot script - * - * @param config ScriptSourceConfig - */ - public void downBotScript(ScriptSourceConfig config) { - config.addCredentials(this); - POST(this.url + "/down-bot-script", config.toXML()); - } - - /** - * Return the list of content types. - * - * @return list of content types - */ - public String[] getTypes() { - return types; - } - /** * Return the access mode types. * * @return access mode types */ public String[] getAccessModes() { - return accessModes; + return accessModes.clone(); } /** @@ -1902,7 +796,7 @@ public class SDKConnection { * @return media access mode types */ public String[] getMediaAccessModes() { - return mediaAccessModes; + return mediaAccessModes.clone(); } /** diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java index 2e3b695f19bfdc803aee2420629da35a0a9a34be..94cebc965c4732370033536e3fd4fef7c8d0016f 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ChatAbility.java @@ -18,24 +18,20 @@ package org.botlibre.sdk.ability; -import org.botlibre.sdk.MainAbility; -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.*; -import org.botlibre.sdk.config.*; -import org.botlibre.sdk.provider.ChatListProvicer; -import org.botlibre.sdk.util.*; import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; -import ohos.agp.components.*; -import ohos.agp.components.element.StateElement; +import ohos.agp.components.Button; +import ohos.agp.components.Component; +import ohos.agp.components.DirectionalLayout; +import ohos.agp.components.Image; +import ohos.agp.components.LayoutScatter; +import ohos.agp.components.ListContainer; +import ohos.agp.components.Text; +import ohos.agp.components.TextField; import ohos.agp.components.webengine.JsCallback; import ohos.agp.components.webengine.WebView; import ohos.agp.utils.LayoutAlignment; -import ohos.agp.window.dialog.IDialog; import ohos.agp.window.dialog.PopupDialog; -import ohos.agp.window.service.Display; -import ohos.agp.window.service.DisplayAttributes; -import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.WindowManager; import ohos.ai.asr.AsrClient; import ohos.ai.asr.AsrIntent; @@ -52,36 +48,51 @@ import ohos.eventhandler.EventRunner; import ohos.eventhandler.InnerEvent; import ohos.media.audio.AudioManager; import ohos.media.audio.AudioRemoteException; -import ohos.media.common.Source; import ohos.media.image.PixelMap; import ohos.media.player.Player; import ohos.multimodalinput.event.TouchEvent; import ohos.utils.PacMap; -import ohos.utils.net.Uri; import ohos.utils.zson.ZSONObject; +import org.botlibre.sdk.MainAbility; +import org.botlibre.sdk.ResourceTable; +import org.botlibre.sdk.ability.actions.HttpAction; +import org.botlibre.sdk.ability.actions.HttpChatAction; +import org.botlibre.sdk.ability.actions.HttpFetchChatAvatarAction; +import org.botlibre.sdk.config.AvatarConfig; +import org.botlibre.sdk.config.ChatConfig; +import org.botlibre.sdk.config.ChatResponse; +import org.botlibre.sdk.config.InstanceConfig; +import org.botlibre.sdk.config.VoiceConfig; +import org.botlibre.sdk.provider.ChatListProvicer; +import org.botlibre.sdk.util.LogUtils; +import org.botlibre.sdk.util.PreferencesUtils; +import org.botlibre.sdk.util.ResUtils; +import org.botlibre.sdk.util.TextStream; +import org.botlibre.sdk.util.ToastUtils; +import org.botlibre.sdk.util.Utils; import java.io.StringWriter; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; /** * Ability for chatting with a bot. * To launch this Ability from your app you can use the HttpFetchAction passing the bot id or name as a config, and launch=true. + * + * @since 2021-04-25 */ @SuppressWarnings("deprecation") public class ChatAbility extends LibreAbility { - protected static final int RESULT_SPEECH = 1; - protected static final int CAPTURE_IMAGE = 2; - protected static final int RESULT_SCAN = 3; - protected static final int CAPTURE_VIDEO = 4; private static final int LIST_CONTAINER = 7; private static final int BEGIN_LISTENING = 8; - protected static boolean DEBUG; + private static boolean DEBUG; - public static Ability ability; + private static Ability ability; private boolean isRecording; - public static boolean isListening; + private static boolean isListening; private EventHandler handler = new EventHandler(EventRunner.current()) { @@ -115,8 +126,8 @@ public class ChatAbility extends LibreAbility { * 语音识别客户端 */ private AsrClient asrClient; - public Component videoLayout; - public Image bigImage; + private Component videoLayout; + private Image bigImage; protected TextField editText; private boolean volumeChecked = true; private Thread thread; @@ -137,16 +148,15 @@ public class ChatAbility extends LibreAbility { protected InstanceConfig instance; private int stateLayouts = 0; private ListContainer scrollView; - public boolean music = false; private double lastReply = System.currentTimeMillis(); - public static List messages = new ArrayList(); - public ChatResponse response; - public Player audioPlayer; - public String currentAudio; + private static final List messages = new ArrayList(); + private ChatResponse response; + private Player audioPlayer; + private String currentAudio; - public boolean videoError; + private boolean videoError; protected volatile boolean wasSpeaking; private boolean active = true; @@ -155,15 +165,12 @@ public class ChatAbility extends LibreAbility { protected String avatarId; protected boolean changingVoice; Player speechPlayer; - protected Random random = new Random(); - protected PixelMap icon; //flag will check if the mic is ON or OFF - public static boolean micLastStat; + private static boolean micLastStat; - private boolean failedOfflineLanguage = false; private boolean threadIsOn = false; /** @@ -199,17 +206,6 @@ public class ChatAbility extends LibreAbility { public void onFinish(String s) { debug("onUtteranceCompleted"); handler.sendEvent(BEGIN_LISTENING); - try { -// if (!MainAbility.disableVideo && !videoError && this.response.isVideo()) { -// this.videoView.post(new Runnable() { -// public void run() { -// cycleVideo(response); -// } -// }); -// } - } catch (Exception exception) { - LogUtils.sop(exception.toString()); - } } @Override @@ -225,7 +221,7 @@ public class ChatAbility extends LibreAbility { @Override public void onEvent(int eventType, PacMap pacMap) { if (eventType == TtsEvent.CREATE_TTS_CLIENT_SUCCESS) { - VoiceConfig voice = MainAbility.voice; + VoiceConfig voice = MainAbility.getVoice(); float pitch = 1; if (voice != null && voice.pitch != null && voice.pitch.length() > 0) { try { @@ -369,7 +365,6 @@ public class ChatAbility extends LibreAbility { restartListening(); } else if (error == AsrError.ERROR_SERVER) { LogUtils.sop("Error: Server Error"); - failedOfflineLanguage = true; restartListening(); } else if (error == AsrError.ERROR_SPEECH_TIMEOUT) { LogUtils.sop("Error: NO speech input"); @@ -450,7 +445,7 @@ public class ChatAbility extends LibreAbility { muteMicBeep(false); //For "scream" issue - micLastStat = MainAbility.listenInBackground; + micLastStat = MainAbility.isListenInBackground(); getWindow().addFlags(WindowManager.LayoutConfig.MARK_SCREEN_ON_ALWAYS); //this.instance = (InstanceConfig) MainAbility.instance; @@ -465,15 +460,15 @@ public class ChatAbility extends LibreAbility { ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { setMicIcon(false, false); - } else if (!MainAbility.listenInBackground) { + } else if (!MainAbility.isListenInBackground()) { setMicIcon(false, false); } //Last time will be saved for the MIC. - if (MainAbility.listenInBackground && MainAbility.handsFreeSpeech) { - microphoneThread(thread); + if (MainAbility.isListenInBackground() && MainAbility.isHandsFreeSpeech()) { + microphoneThread(); } asrClient = AsrClient.createAsrClient(ability).orElse(null); @@ -495,9 +490,6 @@ public class ChatAbility extends LibreAbility { editText = (TextField) findComponentById(ResourceTable.Id_editText); bigImage = (Image) findComponentById(ResourceTable.Id_bigImage); videoLayout = findComponentById(ResourceTable.Id_videoLayout); - - - resetVideoErrorListener(); videoError = false; editText.setFocusChangedListener((component, isFocused) -> { @@ -507,7 +499,7 @@ public class ChatAbility extends LibreAbility { } }); - if (MainAbility.translate) { + if (MainAbility.isTranslate()) { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); } else { findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); @@ -524,40 +516,28 @@ public class ChatAbility extends LibreAbility { }); micButton.setClickedListener(component -> { - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { //set the current volume to the setting. setStreamVolume(); //if its ON Or OFF - Switching back and forth - MainAbility.listenInBackground = !MainAbility.listenInBackground; + MainAbility.setListenInBackground(!MainAbility.isListenInBackground()); //saving the boolean data of MainAbility.listeningInBackground Preferences cookies = PreferencesUtils.getPreferences(ability); - cookies.putBoolean("listenInBackground", MainAbility.listenInBackground); + cookies.putBoolean("listenInBackground", MainAbility.isListenInBackground()); cookies.flushSync(); - if (MainAbility.listenInBackground) { + if (MainAbility.isListenInBackground()) { micLastStat = true; try { - microphoneThread(thread); + microphoneThread(); } catch (Exception ignore) { } beginListening(); } else { micLastStat = false; - microphoneThread(thread); + microphoneThread(); stopListening(); } - } else { -// Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); -// intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, MainAbility.voice.language); -// try { -// startAbilityForResult(intent, RESULT_SPEECH); -// textView.setText(""); -// } catch (AbilityNotFoundException exception) { -// Toast toast = Toast.makeText(getApplicationContext(), -// "Your device doesn't support Speech to Text", -// Toast.LENGTH_SHORT); -// toast.show(); -// } } }); @@ -628,7 +608,7 @@ public class ChatAbility extends LibreAbility { case TouchEvent.POINT_MOVE: return true; case TouchEvent.PRIMARY_POINT_UP: - boolean isVideo = !MainAbility.disableVideo && !videoError && response != null + boolean isVideo = !MainAbility.isDisableVideo() && !videoError && response != null && response.isVideo(); videoLayout = findComponentById(ResourceTable.Id_videoLayout); if (bigImage.getVisibility() == Component.VISIBLE) { @@ -674,16 +654,16 @@ public class ChatAbility extends LibreAbility { final ChatConfig config = new ChatConfig(); //config.instance = instance.id; config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; + config.avatarHD = MainAbility.isHd(); + config.speak = !MainAbility.isDeviceVoice(); // This is required because of a bug in TextToSpeech that prevents onInit being called if an AsynchTask is called... Thread thread1 = new Thread() { public void run() { @@ -706,9 +686,9 @@ public class ChatAbility extends LibreAbility { } //thread for the Microphone - public Thread microphoneThread(Thread thread) { + private Thread microphoneThread() { //make sure its on if it didn't turn off by the user. if 'sleep' is called it will turn the mic off. - if (MainAbility.listenInBackground && threadIsOn) { + if (MainAbility.isListenInBackground() && threadIsOn) { return thread; } //if the user clicked on the Mic while its ON it will turn off and turn the thread off as well. @@ -722,64 +702,32 @@ public class ChatAbility extends LibreAbility { return thread; } //if the user clicked on the Mic while its off it will turn ON the thread. - if (!threadIsOn) { - threadIsOn = true; - active = true; - thread = new Thread() { - @Override - public void run() { - LogUtils.sop("RUNNING"); - while (active) { - LogUtils.sop("ACTIVE"); - if (!isRecording && isListening && (System.currentTimeMillis() - lastReply) > 5000) { - lastReply = System.currentTimeMillis(); - debug("speech death restart"); - restartListening(); - } - try { - Thread.sleep(1500); - } catch (Exception exception) { - } + threadIsOn = true; + active = true; + thread = new Thread() { + @Override + public void run() { + LogUtils.sop("RUNNING"); + while (active) { + LogUtils.sop("ACTIVE"); + if (!isRecording && isListening && (System.currentTimeMillis() - lastReply) > 5000) { + lastReply = System.currentTimeMillis(); + debug("speech death restart"); + restartListening(); + } + try { + Thread.sleep(1500); + } catch (Exception exception) { } } - }; - thread.start(); - } + } + }; + thread.start(); return thread; } - public void resetChat(Component view) { - ChatConfig config = new ChatConfig(); - //config.instance = instance.id; - config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; - } - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - config.speak = !MainAbility.deviceVoice; - HttpAction action = new HttpChatAction(ChatAbility.this, config); - action.execute(); - - editText.setText(""); - messages.clear(); - - //主线程 - handler.sendEvent(LIST_CONTAINER); - - webView.load(null, "", "text/html", "utf-8", null); - } - - public void menuList() { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(this); - DisplayAttributes displayAttributes = display.get().getAttributes(); - + private void menuList() { PopupDialog menuDialog = new PopupDialog(this, null); DirectionalLayout menuComponent = (DirectionalLayout) LayoutScatter.getInstance(this) .parse(ResourceTable.Layout_menu_chat, null, false); @@ -788,20 +736,17 @@ public class ChatAbility extends LibreAbility { DirectionalLayout.LayoutConfig.MATCH_CONTENT); menuDialog.showOnCertainPosition(LayoutAlignment.BOTTOM | LayoutAlignment.LEFT, 10, 280); menuDialog.setAutoClosable(true); - Component.ClickedListener listener=new Component.ClickedListener() { + Component.ClickedListener listener = new Component.ClickedListener() { @Override public void onClick(Component component) { stopListening(); - switch (component.getId()){ + switch (component.getId()) { case ResourceTable.Id_menuItem1: toggleSound(); break; case ResourceTable.Id_menuItem2: toggleDeviceVoice(); break; - case ResourceTable.Id_menuItem3: - changeLanguage(null); - break; case ResourceTable.Id_menuItem4: MicConfiguration(); break; @@ -809,10 +754,10 @@ public class ChatAbility extends LibreAbility { toggleDisableVideo(); break; case ResourceTable.Id_menuItem6: - MainAbility.webm = !MainAbility.webm; + MainAbility.setWebm(!MainAbility.isWebm()); break; case ResourceTable.Id_menuItem7: - MainAbility.hd = !MainAbility.hd; + MainAbility.setHd(!MainAbility.isHd()); break; } } @@ -826,202 +771,30 @@ public class ChatAbility extends LibreAbility { menuComponent.findComponentById(ResourceTable.Id_menuItem6).setClickedListener(listener); menuComponent.findComponentById(ResourceTable.Id_menuItem7).setClickedListener(listener); -// Checkbox checkBox1 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox1); -// Checkbox checkBox2 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox2); -// Checkbox checkBox3 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox3); -// Checkbox checkBox4 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox4); -// Checkbox checkBox5 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox5); -// Checkbox checkBox6 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox6); -// Checkbox checkBox7 = (Checkbox) menuComponent.findComponentById(ResourceTable.Id_checkBox7); -// setCheckBoxShape(checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6); menuDialog.setAlignment(LayoutAlignment.LEFT | LayoutAlignment.BOTTOM); menuDialog.show(); -// statistics.setClickedListener(new Component.ClickedListener() { -// @Override -// public void onClick(Component component) { -// -// menuDialog.hide(); -// menuDialog.remove(); -// } -// }); - } - - private void setCheckBoxShape(Checkbox... checkBoxs) { - StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this, ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this, ResourceTable.Media_unchecked)); - for (Checkbox checkbox : checkBoxs) { - checkbox.setButtonElement(stateElement); - } } - public void resetVideoErrorListener() { -// videoView.setOnErrorListener(new OnErrorListener() { -// @Override -// public boolean onError(MediaPlayer mp, int what, int extra) { -// Log.wtf("Video error", "what:" + what + " extra:" + extra); -// videoError = true; -// return true; -// } -// }); - } @Override protected void onAbilityResult(int requestCode, int resultCode, Intent data) { super.onAbilityResult(requestCode, resultCode, data); - - switch (requestCode) { - case CAPTURE_IMAGE: { - -// if (resultCode == RESULT_OK) { -// //TODO Make camera intent stop app from reseting -// //Uri photoUri = data.getData(); -// //Do what we like with the photo - send to bot, etc -// -// } else if (resultCode == RESULT_CANCELED) { -// textView.setText("Cancelled"); -// submitChat(); -// } - - break; - } - case CAPTURE_VIDEO: { -// if (resultCode == RESULT_OK) { -// Uri videoUri = data.getData(); -// //Do what we would like with the video -// -// } else if (resultCode == RESULT_CANCELED) { -// textView.setText("Cancelled"); -// submitChat(); -// } - break; - } - case RESULT_SPEECH: { -// if (resultCode == RESULT_OK && data != null) { -// -// ArrayList text = data.getStringArrayListParam(RecognizerIntent.EXTRA_RESULTS); -// -// -// textView.setText(text.get(0)); -// submitChat(); -// } - break; - } - } -// IntentResult scanResult = IntentIntegrator.parseAbilityResult(requestCode, resultCode, data); -// if (scanResult != null) { -// textView.setText("lookup " + scanResult.getContents()); -// submitChat(); -// if (scanResult.getContents().startsWith("http")) { -// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(scanResult.getContents())); -// startAbility(intent); -// } -// } - } - - public void flagResponse() { - MainAbility.confirm("Flag bad response?", this, true, (iDialog, i) -> { - switch (i) { - case IDialog.BUTTON1: - ChatConfig config = new ChatConfig(); - //config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; - config.avatar = avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; - } - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - - config.message = "flag"; //text.getText().toString().trim(); - if (config.message.equals("")) { - return; - } - messages.add(config); - handler.sendEvent(LIST_CONTAINER); - - - config.offensive = true; - - - HttpChatAction action = new HttpChatAction(ChatAbility.this, config); - action.execute(); - - editText.setText(""); - resetToolbar(); - - webView.load(null, "thinking...", "text/html", "utf-8", null); - break; - case IDialog.BUTTON2: - break; - } - }); - } - - public void submitCorrection() { - final TextField text = new TextField(this); - MainAbility.prompt("Enter correction to the bot's response (what it should have said)", this, text, (iDialog, i) -> { -// if (instance == null) { -// return; -// } - ChatConfig config = new ChatConfig(); - //config.instance = instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; - config.avatar = avatarId; - if (MainAbility.disableVideo) { - config.avatarFormat = "image"; - } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; - } - config.avatarHD = MainAbility.hd; - - config.message = text.getText().toString().trim(); - if (config.message.equals("")) { - return; - } - messages.add(config); - - handler.sendEvent(LIST_CONTAINER); - - - config.correction = true; - -// Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin); -// config.emote = emoteSpin.getSelectedItem().toString(); -// -// HttpChatAction action = new HttpChatAction(ChatAbility.this, config); -// action.execute(); -// -// TextField v = (TextField) findComponentById(ResourceTable.Id_messageText); -// v.setText(""); -// emoteSpin.setSelection(0); - resetToolbar(); - - webView.load(null, "thinking...", "text/html", "utf-8", null); - }); } - public void submitChat() { + private void submitChat() { ChatConfig config = new ChatConfig(); - //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; - config.speak = !MainAbility.deviceVoice; + config.conversation = MainAbility.getConversation(); + config.speak = !MainAbility.isDeviceVoice(); config.avatar = this.avatarId; - if (MainAbility.translate && MainAbility.voice != null) { - config.language = MainAbility.voice.language; + if (MainAbility.isTranslate() && MainAbility.getVoice() != null) { + config.language = MainAbility.getVoice().language; } - if (MainAbility.disableVideo) { + if (MainAbility.isDisableVideo()) { config.avatarFormat = "image"; } else { - config.avatarFormat = MainAbility.webm ? "webm" : "mp4"; + config.avatarFormat = MainAbility.isWebm() ? "webm" : "mp4"; } - config.avatarHD = MainAbility.hd; + config.avatarHD = MainAbility.isHd(); config.message = editText.getText().toString().trim(); if (config.message.equals("")) { @@ -1057,102 +830,42 @@ public class ChatAbility extends LibreAbility { stopListening(); //its Important for "sleep" "scream" ...etc commands. //this will turn off the mic - MainAbility.listenInBackground = false; + MainAbility.setListenInBackground(false); } - public void toggleSound() { - MainAbility.sound = !MainAbility.sound; + private void toggleSound() { + MainAbility.setSound(!MainAbility.isSound()); resetToolbar(); } - public void toggleHandsFreeSpeech() { - MainAbility.handsFreeSpeech = !MainAbility.handsFreeSpeech; - if (!MainAbility.handsFreeSpeech) { - stopListening(); - } else if (MainAbility.handsFreeSpeech) { - beginListening(); - } - Preferences cookies = PreferencesUtils.getPreferences(this.ability); - cookies.putBoolean("handsfreespeech", MainAbility.handsFreeSpeech); - cookies.flushSync(); - } - - public void toggleDisableVideo() { + private void toggleDisableVideo() { if (this.videoError) { this.videoError = false; - MainAbility.disableVideo = false; - } else { - MainAbility.disableVideo = !MainAbility.disableVideo; - } - } - - public void changeAvatar() { - if (MainAbility.online) { - MainAbility.browsing = true; - BrowseConfig config = new BrowseConfig(); - config.type = "Avatar"; - config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); + MainAbility.setDisableVideo(false); } else { -// Intent intent = getIntent(ability, AvatarSelection.class.getName()); -// startAbility(intent); + MainAbility.setDisableVideo(!MainAbility.isDisableVideo()); } } - public void changeVoice() { - this.changingVoice = true; -// Intent intent = getIntent(ability, ChangeVoiceAbility.class.getName()); -// startAbility(intent); - } - - public void toggleDeviceVoice() { - MainAbility.deviceVoice = !MainAbility.deviceVoice; - } - - public void toggleFlag(Component view) { - flagResponse(); - } - - public void toggleCorrection(Component view) { - submitCorrection(); + private void toggleDeviceVoice() { + MainAbility.setDeviceVoice(!MainAbility.isDeviceVoice()); } - - public void changeLanguage(Component view) { -// MainAbility.changeLanguage(this, (IDialog.ClickedListener) (iDialog, i) -> { -// resetTTS(); -// if (MainAbility.translate) { -// findComponentById(ResourceTable.Id_yandex).setVisibility(Component.VISIBLE); -// } else { -// findComponentById(ResourceTable.Id_yandex).setVisibility(Component.HIDE); -// } -// }); - - - } - - public void resetToolbar() { - if (MainAbility.sound) { - ShapeUtils.setBackground(soundButton,ResourceTable.Media_sound); + private void resetToolbar() { + if (MainAbility.isSound()) { + ResUtils.setBackground(soundButton, ResourceTable.Media_sound); } else { - ShapeUtils.setBackground(soundButton,ResourceTable.Media_mute); + ResUtils.setBackground(soundButton, ResourceTable.Media_mute); } } @Override public void onActive() { - MainAbility.searching = false; - MainAbility.searchingPosts = false; - if (MainAbility.browsing && (MainAbility.instance instanceof AvatarConfig)) { - if (MainAbility.user == null || MainAbility.user.type == null || MainAbility.user.type.isEmpty() || MainAbility.user.type.equals("Basic")) { - //MainAbility.showMessage("You must upgrade to get access to this avatar", this); - //super.onResume(); - //return; - } - this.avatar = (AvatarConfig) MainAbility.instance; + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + if (MainAbility.isBrowsing() && (MainAbility.getInstance() instanceof AvatarConfig)) { + this.avatar = (AvatarConfig) MainAbility.getInstance(); this.avatarId = this.avatar.id; if (this.bigImage.getVisibility() == Component.HIDE) { this.bigImage.setVisibility(Component.VISIBLE); @@ -1165,12 +878,7 @@ public class ChatAbility extends LibreAbility { HttpFetchChatAvatarAction action = new HttpFetchChatAvatarAction(this, avatarConfig); action.execute(); } - MainAbility.browsing = false; - if ((MainAbility.instance instanceof InstanceConfig) && MainAbility.instance.id.equals(this.instance.id)) { - //this.instance = (InstanceConfig) MainAbility.instance; - } else { - //MainAbility.instance = this.instance; - } + MainAbility.setBrowsing(false); if (this.changingVoice) { this.changingVoice = false; resetTTS(); @@ -1178,14 +886,14 @@ public class ChatAbility extends LibreAbility { super.onActive(); } - public void resetTTS() { + private void resetTTS() { ttsClient.stopSpeak(); ttsClient.release(); ttsClient = TtsClient.getInstance(); ttsClient.create(this, ttsListener); } - public String getAvatarIcon(ChatResponse config) { + private String getAvatarIcon(ChatResponse config) { if (this.avatar != null) { return this.avatar.avatar; } @@ -1195,8 +903,8 @@ public class ChatAbility extends LibreAbility { return config.avatar; } - public void MicConfiguration() { - ToastUtils.showCenterToast(ability,"打开麦克风配置"); + private void MicConfiguration() { + ToastUtils.showCenterToast(ability, "打开麦克风配置"); } @Override @@ -1211,8 +919,7 @@ public class ChatAbility extends LibreAbility { } if (this.instance != null) { ChatConfig config = new ChatConfig(); - //config.instance = this.instance.id; - config.conversation = MainAbility.conversation; + config.conversation = MainAbility.getConversation(); config.disconnect = true; HttpChatAction action = new HttpChatAction(this, config); @@ -1310,7 +1017,7 @@ public class ChatAbility extends LibreAbility { return html; } - public void response(final ChatResponse response) { + private void response(final ChatResponse response) { if (speechPlayer != null || ttsClient != null) { try { ttsClient.stopSpeak(); @@ -1354,19 +1061,11 @@ public class ChatAbility extends LibreAbility { final String text = response.message; if (text == null) { - //listContainer.invalidateViews(); -// if (listContainer.getChildCount() > 2) { -// listContainer.setSelection(list.getCount() - 2); -// } beginListening(); return; } messages.add(response); listContainer.getItemProvider().notifyDataChanged(); -// listContainer.invalidateViews(); -// if (listContainer.getCount() > 2) { -// listContainer.setSelection(list.getCount() - 2); -// } String html = Utils.linkHTML(text); if (stateLayouts == 3 || stateLayouts == 4) { @@ -1377,82 +1076,10 @@ public class ChatAbility extends LibreAbility { } webView.load(null, html, "text/html", "utf-8", null); - boolean talk = (text.trim().length() > 0) && (MainAbility.deviceVoice || (this.response.speech != null && this.response.speech.length() > 0)); - if (MainAbility.sound && talk) { - if (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { - -// videoView.setOnPreparedListener(new OnPreparedListener() { -// @Override -// public void onPrepared(MediaPlayer mp) { -// try { -// mp.setLooping(true); -// if (!MainAbility.deviceVoice) { -// // Voice audio -// if (MainAbility.online) { -// speechPlayer = playAudio(response.speech, false, false, false); -// speechPlayer.setOnCompletionListener(new OnCompletionListener() { -// @Override -// public void onCompletion(MediaPlayer mp) { -// mp.release(); -// videoView.post(new Runnable() { -// public void run() { -// cycleVideo(response); -// } -// }); -// runOnUiThread(new Runnable() { -// public void run() { -// if (!music) { -// beginListening(); -// } -// } -// }); -// } -// }); -// -// speechPlayer.play(); -// } -// } else { -// HashMap params = new HashMap(); -// params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id"); -// -// tts.speakText(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params); -// } -// } catch (Exception exception) { -// LogUtils.sop(exception.getMessage()); -// } -// } -// }); - playVideo(this.response.avatarTalk, false); - } else if (talk) { -// if (!MainAbility.deviceVoice) { -// // Voice audio -// if (MainAbility.online) { -// playAudio(this.response.speech, false, false, true); -// } -// } else { -// HashMap params = new HashMap(); -// params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id"); -// -// this.tts.speakText(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params); -// } + boolean talk = (text.trim().length() > 0) && (MainAbility.isDeviceVoice() || (this.response.speech != null && this.response.speech.length() > 0)); + if (MainAbility.isSound() && talk) { + if (!MainAbility.isDisableVideo() && !videoError && this.response.isVideo() && this.response.isVideoTalk()) { } - } else if (talk && (!MainAbility.disableVideo && !videoError && this.response.isVideo() && this.response.avatarTalk != null)) { -// videoView.setOnPreparedListener(new OnPreparedListener() { -// @Override -// public void onPrepared(MediaPlayer mp) { -// mp.setLooping(false); -// } -// }); -// videoView.setOnCompletionListener(new OnCompletionListener() { -// @Override -// public void onCompletion(MediaPlayer mp) { -// videoView.setOnCompletionListener(null); -// cycleVideo(response); -// } -// }); - playVideo(this.response.avatarTalk, false); - handler.sendEvent(BEGIN_LISTENING); - } else { handler.sendEvent(BEGIN_LISTENING); } @@ -1460,7 +1087,7 @@ public class ChatAbility extends LibreAbility { LogUtils.sop(exception.getMessage()); } if (micLastStat) { - MainAbility.listenInBackground = true; + MainAbility.setListenInBackground(true); } } @@ -1471,159 +1098,6 @@ public class ChatAbility extends LibreAbility { super.onInactive(); } - - public void playVideo(String video, boolean loop) { -// if (loop) { -// videoView.setOnPreparedListener(new OnPreparedListener() { -// @Override -// public void onPrepared(MediaPlayer mp) { -// mp.setLooping(true); -// } -// }); -// } -// try { -// Uri videoUri = HttpGetVideoAction.fetchVideo(this, video); -// if (videoUri == null) { -// if (MainAbility.online) { -// videoUri = Uri.parse(MainAbility.connection.fetchImage(video).toURI().toString()); -// } -// } -// videoView.setVideoURI(videoUri); -// videoView.start(); -// } catch (Exception exception) { -// Log.wtf(exception.toString(), exception); -// } - } - - public void cycleVideo(final ChatResponse response) { -// if ((response.avatar2 == null || response.avatar3 == null || response.avatar4 == null || response.avatar5 == null) -// || (response.avatar2.isEmpty() || response.avatar3.isEmpty() || response.avatar4.isEmpty() || response.avatar5.isEmpty()) -// || (response.avatar.equals(response.avatar2) && response.avatar2.equals(response.avatar3) -// && response.avatar3.equals(response.avatar4) && response.avatar4.equals(response.avatar5))) { -// playVideo(response.avatar, true); -// return; -// } -// videoView.setOnPreparedListener(new OnPreparedListener() { -// @Override -// public void onPrepared(MediaPlayer mp) { -// mp.setLooping(false); -// } -// }); -// videoView.setOnCompletionListener(new OnCompletionListener() { -// @Override -// public void onCompletion(MediaPlayer mp) { -// cycleVideo(response); -// } -// }); -// int value = random.nextInt(5); -// String avatar = response.avatar; -// switch (value) { -// case 1: -// avatar = response.avatar2; -// break; -// case 2: -// avatar = response.avatar3; -// break; -// case 3: -// avatar = response.avatar5; -// break; -// case 14: -// avatar = response.avatar4; -// break; -// } -// -// try { -// Uri videoUri = HttpGetVideoAction.fetchVideo(this, avatar); -// if (videoUri == null) { -// if (MainAbility.online) { -// videoUri = Uri.parse(MainAbility.connection.fetchImage(avatar).toURI().toString()); -// } -// } -// videoView.setVideoURI(videoUri); -// videoView.start(); -// } catch (Exception exception) { -// LogUtils.sop(exception.toString()); -// } - } - - public Player playAudio(String audio, boolean loop, boolean cache, boolean start) { - try { - Uri audioUri = null; - if (audioUri == null) { - audioUri = Uri.parse(MainAbility.connection.fetchImage(audio).toURI().toString()); - } - final Player audioPlayer = new Player(ability); - audioPlayer.setSource(new Source(String.valueOf(audioUri))); - audioPlayer.setPlayerCallback(new Player.IPlayerCallback() { - @Override - public void onPrepared() { - - } - - @Override - public void onMessage(int i, int i1) { - - } - - @Override - public void onError(int errorType, int errorCode) { - LogUtils.sop("errorCode" + errorCode); - audioPlayer.stop(); - audioPlayer.release(); - } - - @Override - public void onResolutionChanged(int i, int i1) { - - } - - @Override - public void onPlayBackComplete() { - audioPlayer.release(); - handler.sendEvent(BEGIN_LISTENING); - - } - - @Override - public void onRewindToComplete() { - - } - - @Override - public void onBufferingChange(int i) { - - } - - @Override - public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) { - - } - - @Override - public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) { - - } - }); - audioPlayer.prepare(); - audioPlayer.enableSingleLooping(loop); - if (start) { - audioPlayer.play(); - } - return audioPlayer; - } catch (Exception exception) { - LogUtils.sop(exception.toString()); - return null; - } - } - - public List getMessages() { - return messages; - } - - public void setMessages(List messages) { - this.messages = messages; - } - public ChatResponse getResponse() { return response; } @@ -1671,7 +1145,7 @@ public class ChatAbility extends LibreAbility { private void restartListening() { lastReply = System.currentTimeMillis(); debug("restartListening"); - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { return; } if (!isListening) { @@ -1680,12 +1154,6 @@ public class ChatAbility extends LibreAbility { handler.sendEvent(BEGIN_LISTENING); } - - public void scanBarcode(Component v) { -// IntentIntegrator integrator = new IntentIntegrator(this); -// integrator.initiateScan(); - } - private void setMicIcon(boolean on, boolean recording) { try { if (!on) { @@ -1701,7 +1169,7 @@ public class ChatAbility extends LibreAbility { } - public void debug(final String text) { + private void debug(final String text) { if (!DEBUG) { return; } @@ -1709,24 +1177,20 @@ public class ChatAbility extends LibreAbility { ready.message = text; messages.add(ready); listContainer.getItemProvider().notifyDataChanged(); -// listContainer.invalidateViews(); -// if (listContainer.getCount() > 2) { -// listContainer.setSelection(list.getCount() - 2); -// } } private void muteMicBeep(boolean mute) { - debug("muteMicBeep:" + mute + ":" + MainAbility.volume); + debug("muteMicBeep:" + mute + ":" + MainAbility.getVolume()); AudioManager audioManager = new AudioManager(ability); if (mute) { LogUtils.sop("muteMicBeep : " + 0); //if its true then the Volume will be zero. audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, 0); } else { - LogUtils.sop("muteMicBeep : " + MainAbility.volume); + LogUtils.sop("muteMicBeep : " + MainAbility.getVolume()); //if its false, the Volume will put back on - audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.volume); + audioManager.setVolume(AudioManager.AudioVolumeType.STREAM_MUSIC, MainAbility.getVolume()); } } @@ -1741,7 +1205,7 @@ public class ChatAbility extends LibreAbility { if (volume != 0) { debug("setStreamVolume:" + volume); LogUtils.sop("setStreamVolume : " + volume); - MainAbility.volume = volume; + MainAbility.setVolume(volume); } } @@ -1750,15 +1214,15 @@ public class ChatAbility extends LibreAbility { setStreamVolume(); debug("beginListening:"); try { - if (!MainAbility.handsFreeSpeech) { + if (!MainAbility.isHandsFreeSpeech()) { return; } - if (MainAbility.handsFreeSpeech) { + if (MainAbility.isHandsFreeSpeech()) { muteMicBeep(true); isListening = true; } - if (!MainAbility.listenInBackground) { + if (!MainAbility.isListenInBackground()) { muteMicBeep(false); return; } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java index 5994cf84fbb92a55d08f2c698fb1bb9cb245566c..e10cd9a8c2e51c1700f33357115cfb7e315dff7c 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/CreateUserAbility.java @@ -18,10 +18,6 @@ package org.botlibre.sdk.ability; -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpCreateUserAction; -import org.botlibre.sdk.config.UserConfig; -import org.botlibre.sdk.util.ResUtil; import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Checkbox; @@ -29,20 +25,25 @@ import ohos.agp.components.Component; import ohos.agp.components.ComponentState; import ohos.agp.components.TextField; import ohos.agp.components.element.StateElement; +import org.botlibre.sdk.ResourceTable; +import org.botlibre.sdk.config.UserConfig; +import org.botlibre.sdk.util.ResUtils; /** * Ability for creating a new user. + * + * @since 2021-04-25 */ public class CreateUserAbility extends LibreAbility { private Checkbox showNameCheckBox; + @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.Ability_create_user); super.setUIContent(ResourceTable.Layout_ability_create_user); - showNameCheckBox = (Checkbox)findComponentById(ResourceTable.Id_showNameCheckBox); + showNameCheckBox = (Checkbox) findComponentById(ResourceTable.Id_showNameCheckBox); - Button createButton = (Button)findComponentById(ResourceTable.Id_createButton); + Button createButton = (Button) findComponentById(ResourceTable.Id_createButton); createButton.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { @@ -50,29 +51,27 @@ public class CreateUserAbility extends LibreAbility { } }); - Button helpButton = (Button)findComponentById(ResourceTable.Id_helpButton); + Button helpButton = (Button) findComponentById(ResourceTable.Id_helpButton); helpButton.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - //startOpenAbility(CreateUserAbility.this,HelpAbility.class.getName()); } }); - Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); showNameCheckBox.setButtonElement(stateElement); - } - + } + /** * Create the user. */ public void create() { - UserConfig config = new UserConfig(); - + UserConfig config = new UserConfig(); + TextField text = (TextField) findComponentById(ResourceTable.Id_userText); config.user = text.getText().toString().trim(); text = (TextField) findComponentById(ResourceTable.Id_passwordText); @@ -88,16 +87,13 @@ public class CreateUserAbility extends LibreAbility { text = (TextField) findComponentById(ResourceTable.Id_bioText); config.bio = text.getText().toString().trim(); - config.showName = showNameCheckBox.isChecked(); - - HttpCreateUserAction action = new HttpCreateUserAction(getContext(),this, config); -// action.execute(); + config.showName = showNameCheckBox.isChecked(); } - + /** * Cancel */ public void cancel() { - terminateAbility(); + terminateAbility(); } } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java index daa346dbd05ad8e1340aac93fa9b5257968ace09..a986d14316465337a2f6758bd9db408c18edcba1 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/HelpAbility.java @@ -43,14 +43,13 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen super.onStart(intent); // setContentView(R.layout.ability_help); super.setUIContent(ResourceTable.Layout_ability_help); - MainAbility.online = true; - this.instance = MainAbility.instance; - MainAbility.searching = false; - MainAbility.searchingPosts = false; - //switching to remote Connection. - MainAbility.connection = MainAbility.remoteConnection; + MainAbility.setOnline(true); + this.instance = MainAbility.getInstance(); + MainAbility.setSearching(false); + MainAbility.setSearchingPosts(false); + MainAbility.setConnection(MainAbility.getRemoteConnection()); - MainAbility.instance = this.instance; + MainAbility.setInstance(this.instance); Button faqButton = (Button) findComponentById(ResourceTable.Id_faqButton); @@ -77,10 +76,7 @@ public class HelpAbility extends LibreAbility implements Component.ClickedListen BrowseConfig config = new BrowseConfig(); config.domain = ""; config.type = "Forum"; - config.contentRating = MainAbility.contentRating; - - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); + config.contentRating = MainAbility.getContentRating(); } public void liveSupport() { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/IntentResult.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/IntentResult.java deleted file mode 100644 index fa6cc8a733c5a233c12b2994bc00a37c872af6bb..0000000000000000000000000000000000000000 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/IntentResult.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2009 ZXing authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.ability; - -/** - *

Encapsulates the result of a barcode scan invoked through {@link}.

- * - * @author Sean Owen - */ -public final class IntentResult { - - private final String contents; - private final String formatName; - private final byte[] rawBytes; - private final Integer orientation; - private final String errorCorrectionLevel; - - IntentResult() { - this(null, null, null, null, null); - } - - IntentResult(String contents, - String formatName, - byte[] rawBytes, - Integer orientation, - String errorCorrectionLevel) { - this.contents = contents; - this.formatName = formatName; - this.rawBytes = rawBytes; - this.orientation = orientation; - this.errorCorrectionLevel = errorCorrectionLevel; - } - - /** - * getContents - * - * @return raw content of barcode - */ - public String getContents() { - return contents; - } - - /** - * getFormatName - * - * @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names. - */ - public String getFormatName() { - return formatName; - } - - /** - * getRawBytes - * - * @return raw bytes of the barcode content, if applicable, or null otherwise - */ - public byte[] getRawBytes() { - return rawBytes; - } - - /** - * getOrientation - * - * @return rotation of the image, in degrees, which resulted in a successful scan. May be null. - */ - public Integer getOrientation() { - return orientation; - } - - /** - * getErrorCorrectionLevel - * - * @return name of the error correction level used in the barcode, if applicable - */ - public String getErrorCorrectionLevel() { - return errorCorrectionLevel; - } - - @Override - public String toString() { - StringBuilder dialogText = new StringBuilder(100); - dialogText.append("Format: ").append(formatName).append('\n'); - dialogText.append("Contents: ").append(contents).append('\n'); - int rawBytesLength = rawBytes == null ? 0 : rawBytes.length; - dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n"); - dialogText.append("Orientation: ").append(orientation).append('\n'); - dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n'); - return dialogText.toString(); - } - -} \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java index 8a30f5710b4f81b71b087f51bfbd8ddbc3784d12..543cd67f5f8863eebe9cc0b5b1a542c4f851979f 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/ListTemplateView.java @@ -25,86 +25,18 @@ import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import org.botlibre.sdk.config.OfflineTemplateConfig; -public class ListTemplateView extends /*CreateWebMediumAbility*/Ability { - public static boolean offlineTemplate = false; - List items; +public class ListTemplateView extends Ability { final static String listOfBots [] = {"Empty" , "Basic", "Personal Assistance"}; final static int imagesId [] = {ResourceTable.Media_bot, ResourceTable.Media_bot , ResourceTable.Media_bot}; final static String listOfDec [] = {"A completely empty template loaded with no knowledge or scripts.", "A basic bot template with only responses to common greetings and farewells (hello, goodbye, etc.), and the default bootstrap Self language scripts that understand basic language, 'what is' and 'where is' questions, names, dates, math, and topical questions.", "Template for a Virtual Assistant. This template has command scripts for performing common tasks on such as opening apps, scheduling appointments, and send email."}; - -// ArrayAdapter adapter; -// ListView llview; -// Intent data = new Intent(); -// String temp; -// TextView txt; -// @Override -// public String getType() { -// return "Bot"; -// } + @SuppressWarnings("unchecked") @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_list_view); -// llview = (ListView) findViewById(R.id.theListView); -// txt=(TextView) findViewById(R.id.theTitle); -// txt.setText("Select Template"); -// -// if(offlineTemplate){ -// items = retriveTemplates(); -// -// adapter = new CustomListViewAdapter(this, R.layout.list_item_imager, items); -// llview.setAdapter(adapter); -// -// llview.setOnItemClickListener(new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { -// WebMediumConfig config = new InstanceConfig(); -// OfflineTemplateConfig templates = (OfflineTemplateConfig) (llview.getItemAtPosition(arg2)); -// //saving a template number for getting the icons and pictures of the bot -// saveAllData(MainAbility.launchInstanceName = templates.getTitle(), MainAbility.launchInstanceId = templates.getId(), MainAbility.templateID = arg2); -// config.id = MainAbility.launchInstanceId; -// config.name = MainAbility.launchInstanceName; -// AvatarSelection.saveSelectedAvatar(templates.getTitle()); -// MainAbility.readZipAvatars(ListTemplateView.this, templates.getTitle()); -// MainAbility.offlineSelectedImage = templates.getImageId(); -// HttpAction action = new HttpFetchActionOffline(ListTemplateView.this, config, true); -// action.execute(); -// } -// }); -// offlineTemplate = false; -// return; -// } -// -// -// -// adapter = new ImageListAdapter(this, R.layout.image_list, (List) MainAbility.getAllTemplates(this)); -// llview.setAdapter(adapter); -// -// llview.setOnItemClickListener(new OnItemClickListener() { -// @Override -// public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { -// InstanceConfig templates = (InstanceConfig) (llview.getItemAtPosition(arg2)); -// Toast.makeText(ListTemplateView.this, templates.name + " Selected", Toast.LENGTH_SHORT).show(); -// data.putExtra("template", templates.name); -// setResult(RESULT_OK,data); -// finish(); -// } -// }); -// -// HttpAction action = new HttpGetTemplatesAction(this); -// action.execute(); - - } - - public void saveAllData(String instanceId, String instanceName, int id){ -// SharedPreferences.Editor cookies = MainAbility.current.getPreferences(Context.MODE_PRIVATE).edit(); -// cookies.putString("instanceID", instanceId); -// cookies.putString("instanceName", instanceName); -// cookies.putInt("tempId", id); -// cookies.commit(); } public static List retriveTemplates(){ diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java index 33443529161e668bbe4b0c7cd5cdf6fbe1282b9d..9b024b9e2b3fb618e35e5a5b2c4ba80b953576e4 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/LoginAbility.java @@ -28,50 +28,52 @@ import ohos.agp.components.TextField; /** * Ability for user login. + * + * @since 2021-04-25 */ public class LoginAbility extends LibreAbility implements Component.ClickedListener { - @Override - public void onStart(Intent intent) { - super.onStart(intent); -// setContentView(R.layout.Ability_login); - super.setUIContent(ResourceTable.Layout_ability_login); + @Override + public void onStart(Intent intent) { + super.onStart(intent); + super.setUIContent(ResourceTable.Layout_ability_login); + + Button connectButton = (Button) findComponentById(ResourceTable.Id_connectButton); + connectButton.setClickedListener(this); + Button signUpButton = (Button) findComponentById(ResourceTable.Id_signUpButton); + signUpButton.setClickedListener(this); + } - Button connectButton = (Button)findComponentById(ResourceTable.Id_connectButton); - connectButton.setClickedListener(this); - Button signUpButton = (Button)findComponentById(ResourceTable.Id_signUpButton); - signUpButton.setClickedListener(this); - } - - /** - * Start a chat session with the selected instance and the user. - */ - public void connect() { - TextField text = (TextField) findComponentById(ResourceTable.Id_userText); + /** + * Start a chat session with the selected instance and the user. + */ + public void connect() { + TextField text = (TextField) findComponentById(ResourceTable.Id_userText); String user = text.getText().toString().trim(); text = (TextField) findComponentById(ResourceTable.Id_passwordText); String password = text.getText().toString().trim(); - - UserConfig config = new UserConfig(); - config.user = user; - config.password = password; - HttpConnectAction action = new HttpConnectAction(this, config, true); -// action.execute(); + + UserConfig config = new UserConfig(); + config.user = user; + config.password = password; } - - public void signUp() { - terminateAbility(); - - startOpenAbility(this,CreateUserAbility.class.getName()); - } - @Override - public void onClick(Component component) { - if(component.getId() == ResourceTable.Id_connectButton){//登录 - connect(); - } - if(component.getId() == ResourceTable.Id_signUpButton){// 注册 - signUp(); - } - } + /** + * signUp + */ + public void signUp() { + terminateAbility(); + + startOpenAbility(this, CreateUserAbility.class.getName()); + } + + @Override + public void onClick(Component component) { + if (component.getId() == ResourceTable.Id_connectButton) {//登录 + connect(); + } + if (component.getId() == ResourceTable.Id_signUpButton) {// 注册 + signUp(); + } + } } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java index 3faacbd78a4fae49f83b25756b7032f305bfb666..c19bb3d1d9adbd3f74fb344b42234f17b66f7fee 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/SearchAbility.java @@ -24,7 +24,6 @@ import ohos.agp.components.Checkbox; import ohos.agp.components.Component; import ohos.agp.components.ComponentState; import ohos.agp.components.DirectionalLayout; -import ohos.agp.components.Image; import ohos.agp.components.LayoutScatter; import ohos.agp.components.RadioButton; import ohos.agp.components.Text; @@ -38,26 +37,23 @@ import ohos.agp.window.service.DisplayManager; import ohos.data.preferences.Preferences; import org.botlibre.sdk.MainAbility; import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.ability.actions.HttpGetInstancesAction; import org.botlibre.sdk.ability.dialog.SearchDialogBuilder; import org.botlibre.sdk.ability.listener.SelectListener; import org.botlibre.sdk.config.BrowseConfig; import org.botlibre.sdk.util.PreferencesUtils; -import org.botlibre.sdk.util.ResUtil; +import org.botlibre.sdk.util.ResUtils; import java.util.Optional; /** * Search Ability for searching instances. + * + * @since 2021-04-25 */ public abstract class SearchAbility extends LibreAbility implements SelectListener { final static int TAGTEXT = 3, CATTEXT = 4; - private TextField tagsText, categoriesText; - private Image btnTag, btnCat; - private Text sortSpin, restrictSpin; - private boolean sortSpinOption = true; private int type = 0; private RadioButton publicRadio; private RadioButton radio; @@ -94,24 +90,19 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen @Override public void onStart(Intent intent) { super.onStart(intent); -// setContentView(R.layout.ability_search); super.setUIContent(ResourceTable.Layout_ability_search); - btnCat = (Image) findComponentById(ResourceTable.Id_btnCat); - btnTag = (Image) findComponentById(ResourceTable.Id_btnTag); - tagsText = (TextField) findComponentById(ResourceTable.Id_tagsText); - categoriesText = (TextField) findComponentById(ResourceTable.Id_categoriesText); browseButton = (Button) findComponentById(ResourceTable.Id_browseButton); menuButton = (Button) findComponentById(ResourceTable.Id_menuButton); Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(this + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(this , ResourceTable.Media_checkbox_normal)); checkbox.setButtonElement(stateElement); - checkbox.setChecked(MainAbility.showImages); + checkbox.setChecked(MainAbility.isShowImages()); publicRadio = (RadioButton) findComponentById(ResourceTable.Id_publicRadio); publicRadio.setChecked(true); @@ -163,7 +154,7 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen @Override public void onClick(Component component) { type = 2; - SearchDialogBuilder.with(SearchAbility.this, MainAbility.contentRatings).setSelectInterface(SearchAbility.this); + SearchDialogBuilder.with(SearchAbility.this, MainAbility.getContentRatings()).setSelectInterface(SearchAbility.this); } }); @@ -180,42 +171,9 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen menu(); } }); - -// btnTag.setOnClickListener(new View.OnClickListener() { -// -// @Override -// public void onClick(View v) { -// Intent i = new Intent(SearchAbility.this,ListTagsView.class); -// i.putExtra("type", getType()); -// startAbilityForResult(i,TAGTEXT); -// } -// }); -// btnCat.setOnClickListener(new View.OnClickListener() { -// -// @Override -// public void onClick(View v) { -// Intent i = new Intent(SearchAbility.this,ListCategoriesView.class); -// i.putExtra("type", getType()); -// startAbilityForResult(i,CATTEXT); -// } -// }); - -// HttpAction action = new HttpGetTagsAction(this, getType()); -// action.execute(); -// -// action = new HttpGetCategoriesAction(this, getType()); -// action.execute(); -// MainAbility.searching = !MainAbility.browsing; } -// @Override -// protected void onResume() { -// if(sortSpinOption){ -// sortSpin.setSelection(3); -// sortSpinOption = false; -// } -// super.onResume(); -// } + //Getting Info from the Opened Activities @Override @@ -236,24 +194,12 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen } } - -// public void onDestroy() { -// super.onDestroy(); -// MainAbility.searching = false; -// } - + /** + * browse + */ public void browse() { -// Spinner sortSpin = (Spinner)findComponentById(ResourceTable.Id_sortSpin); -// config.sort = (String)sortSpin.getSelectedItem(); -// Spinner restrictSpin = (Spinner)findComponentById(ResourceTable.Id_restrictSpin); -// config.restrict = (String)restrictSpin.getSelectedItem(); -// //added contentRating -// Spinner contentRating = (Spinner) findComponentById(ResourceTable.Id_ContentRatingSpin); -// MainAbility.contentRating = (String) contentRating.getSelectedItem(); -// config.contentRating = MainAbility.contentRating; - //save contentRating - Preferences editor = PreferencesUtils.getPreferences(MainAbility.current); - editor.putString("contentRating", MainAbility.contentRating); + Preferences editor = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + editor.putString("contentRating", MainAbility.getContentRating()); editor.flushSync(); TextField tagText = (TextField) findComponentById(ResourceTable.Id_tagsText); @@ -263,20 +209,22 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen TextField filterEdit = (TextField) findComponentById(ResourceTable.Id_filterText); config.filter = filterEdit.getText().toString(); Checkbox checkbox = (Checkbox) findComponentById(ResourceTable.Id_imagesCheckBox); - MainAbility.showImages = checkbox.isChecked(); + MainAbility.setShowImages(checkbox.isChecked()); config.type = getType(); - - HttpGetInstancesAction action = new HttpGetInstancesAction(SearchAbility.this, config, MainAbility.browsing); -// action.execute(); } + /** + * setSelect + * + * @return dd + */ public StateElement setSelect() { StateElement stateElement = new StateElement(); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect)); stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, - ResUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); + ResUtils.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal)); return stateElement; } @@ -294,8 +242,16 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen } }; + /** + * getType + * + * @return dd + */ public abstract String getType(); + /** + * menu + */ public void menu() { Optional display = DisplayManager.getInstance().getDefaultDisplay(this); @@ -314,8 +270,6 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen mybots.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { -// browseMyBots(); -// menuDialog.destroy(); } }); @@ -332,31 +286,19 @@ public abstract class SearchAbility extends LibreAbility implements SelectListen browsecategories.setClickedListener(new Component.ClickedListener() { @Override public void onClick(Component component) { - browseCategories(); menuDialog.destroy(); } }); } - public void browseMyBots() { - BrowseConfig config = new BrowseConfig(); - config.type = getType(); - config.typeFilter = "Personal"; - config.contentRating = "Mature"; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config, MainAbility.browsing); -// action.execute(); - } - + /** + * browseFeatured + */ public void browseFeatured() { BrowseConfig config = new BrowseConfig(); config.type = getType(); config.typeFilter = "Featured"; - config.contentRating = MainAbility.contentRating; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config, MainAbility.browsing); -// action.execute(); - } - - public void browseCategories() { + config.contentRating = MainAbility.getContentRating(); } @Override diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java index f74982ea2616e4eb7e4b5bd1f78e9fe4291119ef..220cb17d098bfe72d922bdaa8517a82ebb255123 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpChatAction.java @@ -27,8 +27,6 @@ import ohos.aafwk.ability.Ability; public class HttpChatAction extends HttpAction { ChatConfig config; - ChatResponse response; - public HttpChatAction(Ability ability, ChatConfig config) { super(ability); this.config = config; @@ -37,7 +35,7 @@ public class HttpChatAction extends HttpAction { @Override protected String doInBackground(Void... params) { try { - this.response = MainAbility.connection.chat(this.config); + MainAbility.getConnection().chat(this.config); } catch (Exception exception) { this.exception = exception; } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java index dd3efc61703b320507273886cd2cc06efa6ad289..36a291a302a9e89cd7c2d4decb7133f33ec9e49d 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpConnectAction.java @@ -40,7 +40,7 @@ public class HttpConnectAction extends HttpUIResultAction { public void doInBackground() { loadingDialog(); try { - this.config = MainAbility.connection.connect(config); + this.config = MainAbility.getConnection().connect(config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -55,7 +55,7 @@ public class HttpConnectAction extends HttpUIResultAction { return; } try { - MainAbility.user = this.config; + MainAbility.setUser(this.config); if (this.ability instanceof MainAbility) { ((MainAbility) this.ability).resetView(); } @@ -63,8 +63,8 @@ public class HttpConnectAction extends HttpUIResultAction { if (this.finish) { Preferences cookies = PreferencesUtils.getPreferences(ability); - cookies.putString("user", MainAbility.user.user); - cookies.putString("token", MainAbility.user.token); + cookies.putString("user", MainAbility.getUser().user); + cookies.putString("token", MainAbility.getUser().token); cookies.flushSync(); this.ability.terminateAbility(); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java index 18ff0673a175067bbddea811b127bb7fe77e792a..55b090234499df4524b0de1de372e82e89095549 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpCreateUserAction.java @@ -27,19 +27,17 @@ import ohos.app.Context; public class HttpCreateUserAction extends HttpUIResultAction { UserConfig config; - private Context context; public HttpCreateUserAction(Context context, Ability ability, UserConfig config) { super(ability); this.config = config; - this.context = context; doInBackground(); } // @Override protected void doInBackground() { try { - this.config = MainAbility.connection.create(ability,this.config); + this.config = MainAbility.getConnection().create(ability,this.config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -50,7 +48,7 @@ public class HttpCreateUserAction extends HttpUIResultAction { return; } try { - MainAbility.user = this.config; + MainAbility.setUser(this.config); this.ability.terminateAbility(); } catch (Exception error) { this.exception = error; @@ -59,9 +57,4 @@ public class HttpCreateUserAction extends HttpUIResultAction { } } - -// @Override - public void onPostExecute(String xml) { -// super.onPostExecute(xml); - } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java index fa0b984363739d8ad83de0e2db0f4b0312d6a1ed..f3e80d6bbbd59ae052f6b03e71866a796a2ea9dc 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpFetchChatAvatarAction.java @@ -32,7 +32,7 @@ public class HttpFetchChatAvatarAction extends HttpUIAction { @Override protected String doInBackground(Void... params) { try { - this.config = MainAbility.connection.fetch(this.config); + this.config = MainAbility.getConnection().fetch(this.config); } catch (Exception exception) { this.exception = exception; } @@ -46,7 +46,6 @@ public class HttpFetchChatAvatarAction extends HttpUIAction { return; } try { -// ((ChatAbility)this.ability).resetAvatar(this.config); } catch (Exception error) { this.exception = error; MainAbility.error(this.exception.getMessage(), this.exception, this.ability); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java index d9eb94280adbd2a4b22908c51895ae16ff014009..65e368d2aec6272b4a420d3153675afc48e35cd4 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetInstancesAction.java @@ -30,7 +30,6 @@ public class HttpGetInstancesAction extends HttpUIResultAction { BrowseConfig config; List instances; boolean finish = false; - boolean CustomAvatar = false; public HttpGetInstancesAction(Ability ability, BrowseConfig config) { super(ability); @@ -49,13 +48,12 @@ public class HttpGetInstancesAction extends HttpUIResultAction { super(ability); this.config = config; this.finish = finish; - this.CustomAvatar = CustomAvatar; } public void doInBackground(){ loadingDialog(); try { - this.instances = MainAbility.connection.browse(ability,config); + this.instances = MainAbility.getConnection().browse(ability,config); } catch (Exception exception) { this.exception = exception; removeDialog(); @@ -64,75 +62,15 @@ public class HttpGetInstancesAction extends HttpUIResultAction { onPostExecute(); } -// @Override -// protected String doInBackground(Void... params) { -// -// return ""; -// } -// @Override public void onPostExecute() { -// super.onPostExecute(xml); if (this.exception != null) { return; } - MainAbility.instances = this.instances; + MainAbility.setInstances(this.instances); if (this.finish) { this.ability.terminateAbility(); } -// Intent intent = null; -// MainAbility.browse = this.config; -// if (config.type.equals("Forum")) { -// intent = getIntent(this.ability, BrowseForumAbility.class.getName()); -// } else if (config.type.equals("Channel")) { -// intent = getIntent(this.ability, BrowseChannelAbility.class.getName()); -// } else if (config.type.equals("Domain")) { -// intent = getIntent(this.ability, BrowseDomainAbility.class.getName()); -// } else if (config.type.equals("Avatar")) { -// intent = getIntent(this.ability, BrowseAvatarAbility.class.getName()); -// } else if (config.type.equals("Graphic")) { -// intent = getIntent(this.ability, BrowseGraphicAbility.class.getName()); -// if (this.CustomAvatar) { -// //only happens when CustomAvatar is called -// intent.setParam("dataName", "Custom Avatar"); -// intent.setParam("dataCustomAvatar", true); -// } else { -// intent.setParam("dataCustomAvatar", false); -// } -// -// } else if (config.type.equals("Script")) { -// if (MainAbility.importingBotScript) { -// List onlyScripts = new ArrayList(); -// -// for (int i = 0; i < MainAbility.instances.size(); i++) { -// ScriptConfig config = (ScriptConfig) MainAbility.instances.get(i); -// if (config.categories.contains("Self") || config.categories.contains("AIML")) { -// onlyScripts.add(config); -// } -// } -// MainAbility.instances = onlyScripts; -// } else if (MainAbility.importingBotLog) { -// List onlyScripts = new ArrayList(); -// -// for (int i = 0; i < MainAbility.instances.size(); i++) { -// ScriptConfig config = (ScriptConfig) MainAbility.instances.get(i); -// if (config.categories.contains("Log") || config.categories.contains("AIML") || config.categories.contains("Response")) { -// onlyScripts.add(config); -// } -// } -// MainAbility.instances = onlyScripts; -// } -// intent = getIntent(this.ability, BrowseScriptAbility.class.getName()); -// } else { -// intent = getIntent(this.ability, BrowseAbility.class.getName()); -// } -// -// //for result only happens when RequestAbility calls it. -// if (this.CustomAvatar) { -// this.ability.startAbilityForResult(intent, 1); -// } else { -// this.ability.startAbility(intent); -// } } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java index cf41f9c81aefcfb292699e84e16057d6138f270b..816ff61a8b7569a6e5d84b49e497debac02891d8 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/actions/HttpGetTemplatesAction.java @@ -27,7 +27,6 @@ import javax.swing.text.html.ListView; import java.util.List; public class HttpGetTemplatesAction extends HttpAction { - ListView llview; List templates; public HttpGetTemplatesAction(Ability Ability) { @@ -38,7 +37,7 @@ public class HttpGetTemplatesAction extends HttpAction { @Override protected String doInBackground(Void... params) { try { - this.templates = MainAbility.connection.getTemplates(); + this.templates = MainAbility.getConnection().getTemplates(); } catch (Exception exception) { this.exception = exception; } @@ -50,7 +49,7 @@ public class HttpGetTemplatesAction extends HttpAction { return; } - MainAbility.templates = this.templates; + MainAbility.setTemplates(this.templates); } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java index 6b6e5f7a5b4508551fdbe969d3169da9981da5e5..d494f5a5c0d5691ed9b312035ecb31b737eae4ac 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/adapter/SpinnerAdapter.java @@ -26,7 +26,6 @@ import ohos.agp.components.Text; /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerAdapter extends BaseItemProvider { @@ -42,7 +41,7 @@ public class SpinnerAdapter extends BaseItemProvider { */ public SpinnerAdapter(Ability ability, String[] types) { mAbility = ability; - this.types = types; + this.types = types.clone(); mInflater = LayoutScatter.getInstance(ability); } @@ -85,14 +84,13 @@ public class SpinnerAdapter extends BaseItemProvider { * getComponent * * @param position position - * @param component1 component1 + * @param component component1 * @param componentContainer componentContainer * @return getComponent */ @Override - public Component getComponent(int position, Component component1, ComponentContainer componentContainer) { + public Component getComponent(int position, Component component, ComponentContainer componentContainer) { ViewHolder holder; - Component component = null; if (component == null) { component = mInflater.parse(ResourceTable.Layout_simple_spinner_dropdown_item, componentContainer, false); @@ -109,7 +107,6 @@ public class SpinnerAdapter extends BaseItemProvider { /** * 适配器 * - * @author BotLibre * @since 2021-05-10 */ private static class ViewHolder { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java index a75ead36800635748095bc8f89239222aa9e7517..89f91d097cfe268c52dd02ebb1ea335763a9c482 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/avatar/AvatarSelection.java @@ -42,7 +42,6 @@ public class AvatarSelection extends Ability { final int [] imges = {}; final String [] names = {}; ((Text) findComponentById(ResourceTable.Id_theTitle)).setText("Select Avatar"); - final ListContainer listView = (ListContainer) findComponentById(ResourceTable.Id_theListView); ArrayList items = new ArrayList(); for (int i = 0; i < names.length; i++) { items.add(new OfflineTemplateConfig(imges[i],names[i],null,null)); @@ -51,8 +50,8 @@ public class AvatarSelection extends Ability { } public static void saveSelectedAvatar(String nameOfAvatar) { - MainAbility.nameOfAvatar = nameOfAvatar; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); + MainAbility.setNameOfAvatar(nameOfAvatar); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); cookies.putString("nameOfAvatar", nameOfAvatar); cookies.flushSync(); } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java index b14752da2ad09c11c8ac78699949724ab1af4531..53b2e35a54946f4423d193ec29a3f80f3502c7e1 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/LanguageDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 语言对话框 * - * @author BotLibre * @since 2021-05-10 */ public class LanguageDialogBuilder { @@ -75,13 +74,13 @@ public class LanguageDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.languages); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getLanguages()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer list, Component component, int ii, long ll) { - MainAbility.selectInfo = MainAbility.languages[ii]; // 赋值 选择的选项 - selectListener.selectLanguageItem(MainAbility.languages[ii] + ""); + MainAbility.setSelectInfo(MainAbility.getLanguages()[ii]); // 赋值 选择的选项 + selectListener.selectLanguageItem(MainAbility.getLanguages()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java index 34c67053c103c3e2a87c24dca243287ed1c7ee15..2a575710711b1ba6da83d91e8c2c3447e9ad8d2d 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SearchDialogBuilder.java @@ -35,7 +35,6 @@ import java.util.Optional; /** * 搜索对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SearchDialogBuilder { @@ -51,7 +50,7 @@ public class SearchDialogBuilder { * @param spinStr spinStr */ public SearchDialogBuilder(Ability context,String[] spinStr) { - this.spinStr = spinStr; + this.spinStr = spinStr.clone(); initLayout(context); } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java index d8caef1fa97f65a4d41c50e0c281907e74135f3d..30962a3c1db6da45daa68f8bbc8e25cbcddd8582 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/dialog/SpinnerDialogBuilder.java @@ -36,7 +36,6 @@ import java.util.Optional; /** * 对话框 * - * @author BotLibre * @since 2021-05-10 */ public class SpinnerDialogBuilder { @@ -75,13 +74,13 @@ public class SpinnerDialogBuilder { listContainer = (ListContainer)layout.findComponentById(ResourceTable.Id_typeSpin); - SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.types); + SpinnerAdapter spinner = new SpinnerAdapter(context, MainAbility.getTypes()); listContainer.setItemProvider(spinner); listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() { @Override public void onItemClicked(ListContainer listCon, Component component, int ii, long ll) { - MainAbility.type = MainAbility.types[ii]; // 赋值 选择的选项 - selectListener.selectItem(MainAbility.types[ii] + ""); + MainAbility.setType(MainAbility.getTypes()[ii]); // 赋值 选择的选项 + selectListener.selectItem(MainAbility.getTypes()[ii] + ""); mCommonDialog.hide(); mCommonDialog.remove(); } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java index 1c0419f9a72e8569c22923923a87c3b55b740012..11be68b73ff1b71ce94664e4f9aef3144c07623f 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/HttpChatWarAction.java @@ -18,7 +18,7 @@ public class HttpChatWarAction extends HttpUIAction { protected String doInBackground(Void... params) { try { InstanceConfig instance = new InstanceConfig(); - this.instance = (InstanceConfig) MainAbility.connection.custom("chat-war", this.config, instance); + this.instance = (InstanceConfig) MainAbility.getConnection().custom("chat-war", this.config, instance); } catch (Exception exception) { this.exception = exception; } @@ -31,7 +31,7 @@ public class HttpChatWarAction extends HttpUIAction { if (this.exception != null) { return; } - MainAbility.instance = this.instance; + MainAbility.setInstance(this.instance); } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java index 8f8c105ce54c8f8d1ebf82ecb4e8a047e38e588a..a41ecb34401be012b0717c40ebd5b832e8944616 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/ability/war/StartWarAbility.java @@ -41,154 +41,183 @@ import java.util.List; * Ability for user login. */ public class StartWarAbility extends LibreAbility implements Component.ClickedListener { - protected int browsing = 0; - public static InstanceConfig winner; - public static InstanceConfig looser; - public static InstanceConfig bot1; - public static InstanceConfig bot2; - public static String topic = "Hello"; - public boolean handsFreeSpeechWAS; - - private static long SECRET = 4357845875643L; - - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_start_war); - if(MainAbility.handsFreeSpeech) { - handsFreeSpeechWAS = true; - MainAbility.handsFreeSpeech = false; - } - - ((TextField)findComponentById(ResourceTable.Id_topicText)).setText(topic); - winner = null; - looser = null; - - if (bot1 == null) { - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - String last = cookies.getString("instance", null); - if (last != null && !last.isEmpty()) { - InstanceConfig config = new InstanceConfig(); - config.name = last; - } - } - - MainAbility.connection.setUser(MainAbility.user); - if (MainAbility.browsing) { - if ((MainAbility.instance instanceof InstanceConfig)) { - if (this.browsing == 0) { - bot1 = (InstanceConfig)MainAbility.instance; - Preferences cookies = PreferencesUtils.getPreferences(MainAbility.current); - cookies.putString(bot1.getType(), bot1.name); - cookies.flushSync(); - } else { - bot2 = (InstanceConfig)MainAbility.instance; - } - } - } else if (winner != null) { - try{ - String text = "Last war " + winner.name + " beat " + looser.name + "."; - ((Text)findComponentById(ResourceTable.Id_winner)).setText(text); - ChatWarConfig config = new ChatWarConfig(); - config.winner = winner.id; - config.looser = looser.id; - config.topic = topic; - config.secret = String.valueOf(SECRET + MainAbility.user.user.length()); - HttpChatWarAction action = new HttpChatWarAction(this, config); - action.execute(); - }catch(Exception e){ - MainAbility.showMessage("You must be signed in to vote!", this); - } - } - MainAbility.browsing = false; - resetView(); - } - - public void resetView() { - try{ - List instances = new ArrayList(); - if (bot1 != null) { - instances.add(bot1); - } -// ListContainer list = (ListContainer) findComponentById(ResourceTable.Id_bot1List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); -// instances = new ArrayList(); -// if (bot2 != null) { -// instances.add(bot2); -// } -// list = (ListContainer) findComponentById(ResourceTable.Id_bot2List); -// list.setAdapter(new ImageListAdapter(this, R.layout.image_list, instances)); - }catch(Exception e){ - } - - Button warButton = (Button)findComponentById(ResourceTable.Id_warButton); - warButton.setClickedListener(this); - Button bot2Button = (Button)findComponentById(ResourceTable.Id_bot2Button); - bot2Button.setClickedListener(this); - Button bot1Button = (Button)findComponentById(ResourceTable.Id_bot1Button); - bot1Button.setClickedListener(this); - } - - /** - * Start a new war. - */ - public void war() { + protected int browsing = 0; + private static InstanceConfig winner; + private static InstanceConfig looser; + private static InstanceConfig bot1; + private static InstanceConfig bot2; + private String topic = "Hello"; + public boolean handsFreeSpeechWAS; + + private static long SECRET = 4357845875643L; + + @Override + public void onStart(Intent intent) { + super.onStart(intent); + super.setUIContent(ResourceTable.Layout_ability_start_war); + if (MainAbility.isHandsFreeSpeech()) { + handsFreeSpeechWAS = true; + MainAbility.setHandsFreeSpeech(false); + } + + ((TextField) findComponentById(ResourceTable.Id_topicText)).setText(topic); + setWinner(null); + setLooser(null); + if (bot1 == null) { + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + String last = cookies.getString("instance", null); + if (last != null && !last.isEmpty()) { + InstanceConfig config = new InstanceConfig(); + config.name = last; + } + } + + MainAbility.getConnection().setUser(MainAbility.getUser()); + if (MainAbility.isBrowsing()) { + if ((MainAbility.getInstance() instanceof InstanceConfig)) { + if (this.browsing == 0) { + setBot1((InstanceConfig) MainAbility.getInstance()); + Preferences cookies = PreferencesUtils.getPreferences(MainAbility.getCurrent()); + cookies.putString(bot1.getType(), bot1.name); + cookies.flushSync(); + } else { + setBot2((InstanceConfig) MainAbility.getInstance()); + } + } + } else if (winner != null) { + try { + String text = "Last war " + winner.name + " beat " + looser.name + "."; + ((Text) findComponentById(ResourceTable.Id_winner)).setText(text); + ChatWarConfig config = new ChatWarConfig(); + config.winner = winner.id; + config.looser = looser.id; + config.topic = topic; + config.secret = String.valueOf(SECRET + MainAbility.getUser().user.length()); + HttpChatWarAction action = new HttpChatWarAction(this, config); + action.execute(); + } catch (Exception e) { + MainAbility.showMessage("You must be signed in to vote!", this); + } + } + MainAbility.setBrowsing(false); + resetView(); + } + + public int getBrowsing() { + return browsing; + } + + public void setBrowsing(int browsing) { + this.browsing = browsing; + } + + public static InstanceConfig getWinner() { + return winner; + } + + public static void setWinner(InstanceConfig winne) { + winner = winne; + } + + public static InstanceConfig getLooser() { + return looser; + } + + public static void setLooser(InstanceConfig loose) { + looser = loose; + } + + public static InstanceConfig getBot1() { + return bot1; + } + + public static void setBot1(InstanceConfig bot) { + bot1 = bot; + } + + public static InstanceConfig getBot2() { + return bot2; + } + + public static void setBot2(InstanceConfig bot) { + bot2 = bot; + } + + public void resetView() { + try { + List instances = new ArrayList(); + if (bot1 != null) { + instances.add(bot1); + } + } catch (Exception e) { + } + + Button warButton = (Button) findComponentById(ResourceTable.Id_warButton); + warButton.setClickedListener(this); + Button bot2Button = (Button) findComponentById(ResourceTable.Id_bot2Button); + bot2Button.setClickedListener(this); + Button bot1Button = (Button) findComponentById(ResourceTable.Id_bot1Button); + bot1Button.setClickedListener(this); + } + + /** + * Start a new war. + */ + public void war() { if (bot1 == null || bot2 == null) { - MainAbility.showMessage("Please select two bots to start a war", this); - return; + MainAbility.showMessage("Please select two bots to start a war", this); + return; } - topic = ((TextField)findComponentById(ResourceTable.Id_topicText)).getText().toString(); + + topic = ((TextField) findComponentById(ResourceTable.Id_topicText)).getText(); if (topic == null || topic.isEmpty()) { - MainAbility.showMessage("Please enter a topic", this); - return; + MainAbility.showMessage("Please enter a topic", this); + return; } - MainAbility.instance = bot1; - MainAbility.connection.setUser(null); + MainAbility.setInstance(bot1); + MainAbility.getConnection().setUser(null); // startOpenAbility(this,WarAbility.class.getName()); } - public void browseBot1() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - this.browsing = 0; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); - } - - public void browseBot2() { - BrowseConfig config = new BrowseConfig(); - config.type = "Bot"; - config.sort = "rank"; - config.contentRating = MainAbility.contentRating; - - MainAbility.browsing = true; - MainAbility.instance = null; - this.browsing = 1; - HttpGetInstancesAction action = new HttpGetInstancesAction(this, config); -// action.execute(); - } - - @Override - protected void onBackground() { - if(handsFreeSpeechWAS){ - MainAbility.handsFreeSpeech = true; - } - super.onBackground(); - } - - @Override - public void onClick(Component component) { - if(component.getId() == ResourceTable.Id_warButton){ - war(); - } - if(component.getId() == ResourceTable.Id_bot1Button){ - browseBot1(); - } - if(component.getId() == ResourceTable.Id_bot2Button){ - browseBot2(); - } - } + public void browseBot1() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(true); + this.browsing = 0; + } + + public void browseBot2() { + BrowseConfig config = new BrowseConfig(); + config.type = "Bot"; + config.sort = "rank"; + config.contentRating = MainAbility.getContentRating(); + + MainAbility.setBrowsing(true); + MainAbility.setInstance(null); + this.browsing = 1; + } + + @Override + protected void onBackground() { + if (handsFreeSpeechWAS) { + MainAbility.setHandsFreeSpeech(true); + } + super.onBackground(); + } + + @Override + public void onClick(Component component) { + if (component.getId() == ResourceTable.Id_warButton) { + war(); + } + if (component.getId() == ResourceTable.Id_bot1Button) { + browseBot1(); + } + if (component.getId() == ResourceTable.Id_bot2Button) { + browseBot2(); + } + } } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java index d37dd0797d08c1d2da7ea52d7fa1fb4058425d3c..58cab3253a8b0588fe1aa9c30d2c7d3988e5b620 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/AvatarMedia.java @@ -31,7 +31,7 @@ import org.w3c.dom.Element; public class AvatarMedia extends Config { public String mediaId; public String name; - public String type; + public String types; public String media; public String emotions; public String actions; @@ -44,7 +44,7 @@ public class AvatarMedia extends Config { this.mediaId = element.getAttribute("mediaId"); this.name = element.getAttribute("name"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.media = element.getAttribute("media"); this.emotions = element.getAttribute("emotions"); this.actions = element.getAttribute("actions"); @@ -63,8 +63,8 @@ public class AvatarMedia extends Config { if (this.name != null) { writer.write(" name=\"" + this.name + "\""); } - if (this.type != null) { - writer.write(" type=\"" + this.type + "\""); + if (this.types != null) { + writer.write(" type=\"" + this.types + "\""); } if (this.emotions != null) { writer.write(" emotions=\"" + this.emotions + "\""); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java index 992215f546b61796584a2dad19948c43847f057b..480720cf9f9019f0ac911425d07d013069068f60 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/BrowseConfig.java @@ -24,7 +24,7 @@ import java.io.StringWriter; * DTO for XML browse options. */ public class BrowseConfig extends Config { - public String type; + public String types; public String typeFilter; public String category; public String tag; @@ -39,7 +39,7 @@ public class BrowseConfig extends Config { StringWriter writer = new StringWriter(); writer.write(""); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java index dc2b363caa5cdff7ea26f35508506ccabf8f9c72..893cd6f4b7ca5911fee6c7d964d7fbbed1f1158b 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ConversationConfig.java @@ -35,14 +35,14 @@ import org.w3c.dom.NodeList; public class ConversationConfig extends Config { public String id; public String creationDate; - public String type; + public String types; public List input; public void parseXML(Element element) { this.id = element.getAttribute("id"); this.creationDate = element.getAttribute("creationDate"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); NodeList nodes = element.getElementsByTagName("input"); if (nodes != null && nodes.getLength() > 0) { @@ -55,14 +55,4 @@ public class ConversationConfig extends Config { } } } - - public String displayCreationDate() { - try { - SimpleDateFormat formater = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); - Date date = formater.parse(creationDate); - return Utils.displayTimestamp(date); - } catch (Exception exception) { - return creationDate; - } - } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java index 50ed66a264cf38d85254c5d1ab3390b0a1ed6788..e8133daa45b816ee85ca962bbdbf03dd1fec28b6 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ForumPostConfig.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.Objects; import org.botlibre.sdk.util.Utils; import org.w3c.dom.Element; @@ -69,7 +70,12 @@ public class ForumPostConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, topic, summary, details, detailsText, forum, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isFeatured, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, replyCount, parent, avatar, replies); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java index a706bfb66db5664425fea2d3940d01fe3154768b..014f21dd000859d3ba1e03707161a5e73b821d6e 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/IssueConfig.java @@ -27,6 +27,7 @@ import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; /** @@ -65,7 +66,12 @@ public class IssueConfig extends Config { } return false; } - + + @Override + public int hashCode() { + return Objects.hash(id, title, priority, summary, details, detailsText, tracker, tags, thumbsUp, thumbsDown, stars, isAdmin, isFlagged, flaggedReason, isPriority, creator, creationDate, views, dailyViews, weeklyViews, monthlyViews, avatar); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java index 3237a0a40ffdeff201f2f67b22c0333050e02d21..3f74f813a34cbdca218750e4a8b47b6518aed4df 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/MediaConfig.java @@ -29,7 +29,7 @@ import org.w3c.dom.Element; public class MediaConfig extends Config { public long id; public String name; - public String type; + public String types; public String file; public String key; @@ -38,7 +38,7 @@ public class MediaConfig extends Config { this.id = Long.valueOf(element.getAttribute("id")); this.name = element.getAttribute("name"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.file = element.getAttribute("file"); this.key = element.getAttribute("key"); } @@ -55,8 +55,8 @@ public class MediaConfig extends Config { if (this.name != null) { writer.write(" name=\"" + this.name + "\""); } - if (this.type != null) { - writer.write(" type=\"" + this.type + "\""); + if (this.types != null) { + writer.write(" type=\"" + this.types + "\""); } if (this.file != null) { writer.write(" file=\"" + this.file + "\""); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java index e0963e48207c8c00f6e5824e34d511d1bb8f2469..bf74806b009d1bb46c59b47e6fda23172871cfaf 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/ResponseConfig.java @@ -19,6 +19,7 @@ package org.botlibre.sdk.config; import java.io.StringWriter; +import java.util.Objects; import ohos.utils.zson.ZSONException; import ohos.utils.zson.ZSONObject; @@ -73,6 +74,11 @@ public class ResponseConfig extends Config { return super.equals(object); } + @Override + public int hashCode() { + return Objects.hash(questionId, responseId, question, response, previous, onRepeat, label, topic, keywords, required, emotions, actions, poses, noRepeat, requirePrevious, requireTopic, flagged, correctness, command); + } + public String toXML() { StringWriter writer = new StringWriter(); writeXML(writer); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java index 6e2324f4aab4c99d82c91c539df79ba343f37f9b..426ea2ac97afe9eef2269db13da4181b9082022a 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/config/UserConfig.java @@ -22,6 +22,7 @@ import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; +import java.util.Objects; import org.botlibre.sdk.SDKConnection; import org.w3c.dom.Element; @@ -57,7 +58,7 @@ public class UserConfig extends Config { public String joined; public String lastConnect; - public String type; + public String types; public boolean isFlagged; public String flaggedReason; @@ -98,6 +99,11 @@ public class UserConfig extends Config { return this.user != null && this.user.equals(((UserConfig)object).user); } + @Override + public int hashCode() { + return Objects.hash(password, newPassword, hint, name, showName, email, website, bio, over18, avatar, connects, bots, posts, messages, forums, scripts, graphics, avatars, domains, channels, joined, lastConnect, type, isFlagged, flaggedReason); + } + public void parseXML(Element element) { this.user = element.getAttribute("user"); this.name = element.getAttribute("name"); @@ -118,7 +124,7 @@ public class UserConfig extends Config { this.domains = element.getAttribute("domains"); this.joined = element.getAttribute("joined"); this.lastConnect = element.getAttribute("lastConnect"); - this.type = element.getAttribute("type"); + this.types = element.getAttribute("type"); this.isFlagged = Boolean.valueOf(element.getAttribute("isFlagged")); Node node = element.getElementsByTagName("bio").item(0); diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java index 9c381caa72cae66fc20a0de93c91808e7bc54586..618facbb53761e9b3a5afbfddc1ed96a218b08c4 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/micro/MicroConnection.java @@ -56,9 +56,8 @@ import org.botlibre.sdk.Credentials; public class MicroConnection extends SDKConnection implements TextListener { private WebMediumConfig config; protected Map activeBots = new HashMap(); - public static AvatarConfig avatarConfig; public TextOutput message; - public static Bot bot; + private static Bot bot; /** * Create a micro/offline SDK connection. @@ -120,20 +119,6 @@ public class MicroConnection extends SDKConnection implements TextListener { } // this method will return a Bot with the default instance Bot bot = getBot(this.config.id); - try { - int i = 0; - while (i <= 4) { - if (bot == null) { - wait(1000); - bot = this.activeBots.get(config.instance); - } else if (bot != null) { - break; - } - i++; - } - } catch (Exception e) { - - } if (bot == null) { this.exception = new SDKException("Bot doesn't exists!"); @@ -161,10 +146,6 @@ public class MicroConnection extends SDKConnection implements TextListener { if (this.message != null) { response.message = this.message.getMessage(); response.command = bot.avatar().getCommand(); - try { - avatarConfig.chatReply(response); - } catch (Exception e) { - } } } catch (InterruptedException exception) { this.exception = new SDKException("Timeout waiting for response"); @@ -181,29 +162,14 @@ public class MicroConnection extends SDKConnection implements TextListener { */ public T fetch(T config) { this.config = config; - MicroMemory.storageFileName = config.name; int id = Integer.parseInt(config.id); - bot = loadBot(config.name, id); + setBot(loadBot(config.name, id)); addBot(config.id, bot); if (!(config instanceof InstanceConfig)) { return super.fetch(config); } return config; } - - /** - * Return the bot's voice configuration. - * - * @param config InstanceConfig - * @return VoiceConfig - */ - public VoiceConfig getVoice(InstanceConfig config) { - VoiceConfig voice = new VoiceConfig(); - voice.nativeVoice = true; - voice.language = "en"; - return voice; - } - /** * sendMessage * @@ -211,7 +177,6 @@ public class MicroConnection extends SDKConnection implements TextListener { */ public synchronized void sendMessage(TextOutput message) { this.message = message; - notifyAll(); } /** @@ -223,13 +188,11 @@ public class MicroConnection extends SDKConnection implements TextListener { */ public Bot loadBot(String name, int id) { boolean exists = MicroMemory.checkExists(); - Bot.CONFIG_FILE = "config.xml"; - Bot bot = Bot.createInstance(Bot.CONFIG_FILE, name, true); + Bot bot = Bot.createInstance("config.xml", name, true); bot.setName(name); Language language = bot.mind().getThought(Language.class); language.setLearnGrammar(false); - //if (id != 2) { language.setLearningMode(LearningMode.Disabled); Comprehension comprehension = bot.mind().getThought(Comprehension.class); comprehension.setEnabled(false); @@ -237,7 +200,6 @@ public class MicroConnection extends SDKConnection implements TextListener { consciousness.setEnabled(false); Sense sense = bot.awareness().getSense(Wiktionary.class); sense.setIsEnabled(false); - //} if (!exists) { try { @@ -302,4 +264,8 @@ public class MicroConnection extends SDKConnection implements TextListener { memory.save(); return user; } + + public static void setBot(Bot bot) { + MicroConnection.bot = bot; + } } \ No newline at end of file diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java index 8f99e2936c02291eeaa0a631307201d7ae73faa8..d065bccaf523bc525296a579b1cf3918a689478b 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/provider/ChatListProvicer.java @@ -46,7 +46,6 @@ public class ChatListProvicer extends BaseItemProvider { } Object message = getItem(i); Text messageView = (Text) cpt.findComponentById(ResourceTable.Id_messageView); - Image userView = (Image) cpt.findComponentById(ResourceTable.Id_userView); if (message instanceof ChatConfig) { ChatConfig config = (ChatConfig) message; messageView.setText(config.message); @@ -54,7 +53,6 @@ public class ChatListProvicer extends BaseItemProvider { } else if (message instanceof ChatResponse) { ChatResponse config = (ChatResponse) message; messageView.setText(Utils.stripTags(config.message)); - String avatar = ((ChatAbility) this.slice).getAvatarIcon(config); } return cpt; diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java deleted file mode 100644 index 49fb24e5d366193acb5d67f0919bfa8d7e905647..0000000000000000000000000000000000000000 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/slice/MainAbilitySlice.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.botlibre.sdk.slice; - -import org.botlibre.sdk.ResourceTable; -import org.botlibre.sdk.util.LogUtils; -import ohos.aafwk.ability.AbilitySlice; -import ohos.aafwk.content.Intent; -import ohos.agp.window.dialog.CommonDialog; -import ohos.agp.window.dialog.IDialog; - -public class MainAbilitySlice extends AbilitySlice { - @Override - public void onStart(Intent intent) { - super.onStart(intent); - super.setUIContent(ResourceTable.Layout_ability_main); - } - - @Override - public void onActive() { - super.onActive(); - } - - @Override - public void onForeground(Intent intent) { - super.onForeground(intent); - } - - - public static void showMessage(String title, String message, AbilitySlice Ability) { - try { - CommonDialog dialog = new CommonDialog(Ability); - dialog.setContentText(message); - if (title != null) { - dialog.setTitleText(title); - } - dialog.setButton(CommonDialog.BUTTON1, "OK", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - } - }); - dialog.show(); - } catch (Exception exception) { - LogUtils.e("showMessage", exception.toString()); - } - } - - public static void showMessage(String message, AbilitySlice Ability) { - showMessage(null, message, Ability); - } -} diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java index bce9ffe8c242a71cc0aa5b3ac96ba64fb6084abd..0d2563939d55dad1304e1a72365ab87737b6f8bf 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/AsyncTask.java @@ -36,7 +36,6 @@ import java.util.concurrent.atomic.AtomicInteger; * @param * @param * @param - * @author:hhh * @since 2021-05-08 */ public abstract class AsyncTask { @@ -82,7 +81,7 @@ public abstract class AsyncTask { protected void done() { super.done(); try { - postResult(get()); + postResult(super.get()); } catch (InterruptedException | ExecutionException e) { e.getMessage(); } @@ -118,7 +117,6 @@ public abstract class AsyncTask { /** * 可以回调的一些函数 */ - @MainThread protected void onPreExecute() { } @@ -135,14 +133,12 @@ public abstract class AsyncTask { * * @param result */ - @MainThread protected void onPostExecute(Result result) { } /** * onCancelled */ - @MainThread protected void onCancelled() { } @@ -151,14 +147,12 @@ public abstract class AsyncTask { * * @param progress */ - @MainThread protected void onProgressUpdate(Progress... progress) { } /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ private static class InnerUiHandler extends EventHandler { @@ -198,7 +192,6 @@ public abstract class AsyncTask { /** * InnerUiHandler * - * @author:hello * @since 2021-04-25 */ public enum Status { @@ -262,7 +255,6 @@ public abstract class AsyncTask { * * @param * @param - * @author:hello * @since 2021-04-25 */ private abstract static class WorkRunnable implements Callable { @@ -276,7 +268,6 @@ public abstract class AsyncTask { * InnerUiHandler * * @param - * @author:hello * @since 2021-04-25 */ private static class AsyncTaskResult { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Constant.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Constant.java index 2038bcd9f3ab6f31ef3ed232145ee810afff36f1..63627c1e327c2fae500dff3b238b6e5d829fbc67 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Constant.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Constant.java @@ -18,7 +18,6 @@ package org.botlibre.sdk.util; /** * 常量工具类 * - * @author: ColorPicker * @since 2021-04-16 */ public final class Constant { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java index 9629cb0ba876eae2c207eba41ac2a4fb6a79441b..1ef2134a46013a0cd655657d0b6a06d492ce86fd 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/LogUtils.java @@ -21,7 +21,6 @@ import ohos.hiviewdfx.HiLogLabel; /** * Log工具类 * - * @author:turnlayout * @since 2021-04-16 */ public final class LogUtils { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/MainThread.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/MainThread.java deleted file mode 100644 index 22487dec32617bd1033c3ac26a49d2f9ebedf86a..0000000000000000000000000000000000000000 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/MainThread.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.CONSTRUCTOR; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.PARAMETER; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.CLASS; - -/** - * 注解 - * - * @author:turnlayout - * @since 2021-04-16 - */ -@Documented -@Retention(CLASS) -@Target({METHOD, CONSTRUCTOR, TYPE, PARAMETER}) -public @interface MainThread { -} diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java index d98fdc2b0dc053c102ce53400fabd58f5cb962d8..518720442318ce7324b8c6cd609785d91e9fcfb9 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/PreferencesUtils.java @@ -23,7 +23,6 @@ import ohos.data.preferences.Preferences; /** * PreferencesUtils * - * @author:username * @since 2021-05-10 */ public class PreferencesUtils { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java deleted file mode 100644 index 01cbef0229d910b8d378736f00c67bee32cf80cd..0000000000000000000000000000000000000000 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtil.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import ohos.agp.components.AttrSet; -import ohos.agp.components.element.Element; -import ohos.agp.components.element.ElementScatter; -import ohos.agp.components.element.PixelMapElement; -import ohos.app.Context; -import ohos.global.resource.NotExistException; -import ohos.global.resource.RawFileEntry; -import ohos.global.resource.Resource; -import ohos.global.resource.ResourceManager; -import ohos.global.resource.WrongTypeException; -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; - -import java.io.IOException; -import java.util.Optional; - -/** - * ResUtil工具类 - * - * @author:turnlayout - * @since 2021-04-16 - */ -public class ResUtil { - private ResUtil() { - } - - /** - * get the path from id - * - * @param context the context - * @param id - * @return the path from id - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - return path; - } - return path; - } - - /** - * get the color - * - * @param context the context - * @param id - * @return the color - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get string - * - * @param context the context - * @param id - * @return string of the given id - */ - public static String getString(Context context, int id) { - String result = ""; - if (context == null) { - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - return result; - } - try { - result = manager.getElement(id).getString(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * getPreferences - * - * @param context - * @param id - * @param format - * @return str - */ - public static String getString(Context context, int id, Object... format) { - return String.format(getString(context, id), format); - } - - /** - * get the pixel map - * - * @param context the context - * @param id - * @return the pixel map - */ - public static Optional getPixelMap(Context context, int id) { - String path = getPathById(context, id); - if (path == null || path.length() <= 0) { - return Optional.empty(); - } - RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); - ImageSource.SourceOptions options = new ImageSource.SourceOptions(); - options.formatHint = "image/png"; - ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); - try { - Resource asset = assetManager.openRawFile(); - ImageSource source = ImageSource.create(asset, options); - return Optional.ofNullable(source.createPixelmap(decodingOptions)); - } catch (IOException e) { - return Optional.empty(); - } - } - - /** - * get the Pixel Map Element - * - * @param context the context - * @param resId - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * getElement - * - * @param context - * @param resId - * @return Element - */ - public static Element getElement(Context context, int resId) { - return ElementScatter.getInstance(context).parse(resId); - } - - /** - * getColorValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getColorValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getColorValue().getValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getDimensionValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getDimensionValue(); - if (value != 0) { - return value; - } - return defaultValue; - } - - /** - * getDimensionValue - * - * @param attrSet - * @param name - * @param defaultValue - * @return value - */ - public static int getIntValue(AttrSet attrSet, String name, int defaultValue) { - int value = attrSet.getAttr(name).get().getIntegerValue(); - if (value != 0) { - return value; - } - return defaultValue; - } -} - diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java index 07761b975827f0205af3568e5d2341f2d0e8348a..bb0d9f8e58fbc7d68e2ef1a36e1f5b7b4512e9c0 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ResUtils.java @@ -15,43 +15,33 @@ package org.botlibre.sdk.util; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.element.Element; +import ohos.aafwk.ability.Ability; +import ohos.agp.components.Button; +import ohos.agp.components.Checkbox; +import ohos.agp.components.ComponentState; import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.ShapeElement; -import ohos.agp.components.element.VectorElement; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; -import ohos.agp.utils.Rect; +import ohos.agp.components.element.StateElement; import ohos.app.Context; import ohos.global.resource.NotExistException; import ohos.global.resource.RawFileEntry; import ohos.global.resource.Resource; import ohos.global.resource.ResourceManager; import ohos.global.resource.WrongTypeException; -import ohos.hiviewdfx.HiLog; -import ohos.hiviewdfx.HiLogLabel; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; -import ohos.media.image.common.PixelFormat; -import ohos.media.image.common.Size; +import org.botlibre.sdk.ResourceTable; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; /** * 资源工具类 * - * @author:hello * @since 2021-04-25 */ -public class ResUtils { +public final class ResUtils { private static final String TAG = "ResUtil"; - private static final int CONSTANT = 160; + private static final float CONSTANT = 160; private ResUtils() { } @@ -63,19 +53,8 @@ public class ResUtils { * @param vp vp * @return px */ - public static int vpToPx(Context context, float vp) { - return (int) (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp); - } - - /** - * px转vp - * - * @param context 上下文 - * @param px px - * @return vp - */ - public static int pxTovp(Context context, float px) { - return (int) (px / (context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT)); + public static float vpToPx(Context context, float vp) { + return context.getResourceManager().getDeviceCapability().screenDensity / CONSTANT * vp; } /** @@ -84,139 +63,10 @@ public class ResUtils { * @param context 上下文 * @return 屏幕的宽,单位px */ - public static int getScreenWidth(Context context) { + public static float getScreenWidth(Context context) { return vpToPx(context, context.getResourceManager().getDeviceCapability().width); } - /** - * 获取屏幕的高 - * - * @param context 上下文 - * @return 屏幕的高,单位px - */ - public static int getScreenHeight(Context context) { - return vpToPx(context, context.getResourceManager().getDeviceCapability().height); - } - - /** - * 通过资源id获取路径 - * - * @param context 上下文 - * @param id 资源id - * @return 资源路径 - */ - public static String getPathById(Context context, int id) { - String path = ""; - if (context == null) { - LogUtils.e("getPathById -> get null context"); - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getPathById -> get null ResourceManager"); - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException | NotExistException | WrongTypeException e) { - LogUtils.e("getPathById: " + e.getMessage()); - } - return path; - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static Color getNewColor(Context context, int id) { - return new Color(getColor(context, id)); - } - - /** - * 通过资源id获取颜色 - * - * @param context 上下文 - * @param id 资源Id - * @return 颜色 - */ - public static int getColor(Context context, int id) { - int result = 0; - if (context == null) { - LogUtils.e("getColor -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getColor -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getColor: " + e.getMessage()); - } - return result; - } - - /** - * 通过资源id获取尺寸 - * - * @param context 上下文 - * @param id 资源Id - * @return 尺寸 - */ - public static float getDimen(Context context, int id) { - float result = 0; - if (context == null) { - LogUtils.e("getDimen -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException | WrongTypeException | NotExistException e) { - LogUtils.e("getDimen: " + e.getMessage()); - } - return result; - } - - /** - * getBoolean - * - * @param context the context - * @param id the id - * @return get the boolean dimen value - */ - public static boolean getBoolean(Context context, int id) { - boolean result = false; - if (context == null) { - LogUtils.e("getBoolean -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtils.e("getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException e) { - LogUtils.e("getBoolean -> IOException"); - } catch (NotExistException e) { - LogUtils.e("getBoolean -> NotExistException"); - } catch (WrongTypeException e) { - LogUtils.e("getBoolean -> WrongTypeException"); - } - return result; - } - /** * get string * @@ -226,143 +76,74 @@ public class ResUtils { */ public static String getString(Context context, int id) { String result = ""; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null context"); - return result; - } ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> get null ResourceManager"); - return result; - } try { result = manager.getElement(id).getString(); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> IOException"); + LogUtils.e("getString ->IOException"); } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> NotExistException"); + LogUtils.e("getString -> NotExistException"); } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getString -> WrongTypeException"); + LogUtils.e("getString -> WrongTypeException"); } return result; } /** - * get the string array + * 设置button背景 * - * @param context the context - * @param id the string array id - * @return the string array + * @param button + * @param resId */ - public static String[] getStringArray(Context context, int id) { - String[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> get null ResourceManager"); - return result; - } + public static void setBackground(Button button, int resId) { + Resource bgResource = null; + button.setBackground(null); try { - result = manager.getElement(id).getStringArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getStringArray -> WrongTypeException"); + bgResource = button.getResourceManager().getResource(resId); + PixelMapElement pixBg = new PixelMapElement(bgResource); + button.setAroundElements(pixBg, null, null, null); + } catch (IOException | NotExistException e) { + e.getMessage(); } - return result; } /** - * get the int + * 设置button背景 * - * @param context the context - * @param id the int array - * @return the int array + * @param ability + * @param checkbox */ - public static int getInt(Context context, int id) { - int result = 0; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getInteger(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getInt -> WrongTypeException"); - } - return result; + public static void setCheckboxBg(Ability ability, Checkbox checkbox) { + StateElement stateElement = new StateElement(); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_checked)); + stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtils.getPixelMapDrawable(ability, + ResourceTable.Media_unchecked)); + checkbox.setButtonElement(stateElement); } /** - * get the int array - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int[] getIntArray(Context context, int id) { - int[] result = null; - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> IOException"); - } catch (NotExistException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> NotExistException"); - } catch (WrongTypeException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getIntArray -> WrongTypeException"); - } - return result; - } - - /** - * get the vector drawable + * get the Pixel Map Element * * @param context the context - * @param id the drawable id - * @return the vector drawable + * @param resId + * @return the Pixel Map Element */ - public static VectorElement getVectorDrawable(Context context, int id) { - if (context == null) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getVectorDrawable -> get null context"); - return null; - } - return new VectorElement(context, id); + public static PixelMapElement getPixelMapDrawable(Context context, int resId) { + Optional optional = getPixelMap(context, resId); + return optional.map(PixelMapElement::new).orElse(null); } /** * get the pixel map * * @param context the context - * @param id the id + * @param id * @return the pixel map */ public static Optional getPixelMap(Context context, int id) { String path = getPathById(context, id); - if (path.isEmpty()) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> get empty path"); + if (path == null || path.length() <= 0) { return Optional.empty(); } RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); @@ -374,223 +155,31 @@ public class ResUtils { ImageSource source = ImageSource.create(asset, options); return Optional.ofNullable(source.createPixelmap(decodingOptions)); } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "getPixelMap -> IOException"); + return Optional.empty(); } - return Optional.empty(); } /** - * get the Pixel Map Element + * get the path from id * * @param context the context - * @param resId the res id - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement - */ - public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle, - float sweepAngle) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } - - /** - * get the Element - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param rect the rect - * @return the Element + * @param id + * @return the path from id */ - public static Element getCustomCircleGradientDrawable(int thickness, Color inside, Color border, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.OVAL); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - element.setBounds(rect); - return element; - } - - /** - * get the Element - * - * @param inside the inside color - * @param rect the rect - * @return the Element - */ - public static Element getCustomRectGradientDrawable(Color inside, Rect rect) { - ShapeElement element = new ShapeElement(); - element.setShape(ShapeElement.RECTANGLE); - element.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); - element.setBounds(rect); - return element; - } - - /** - * 根据Resource获取背景(图片) - * - * @param resource 资源 - * @return 位图背景 - * @throws IOException - * @throws NotExistException - */ - public static PixelMapElement prepareElement(Resource resource) throws IOException, NotExistException { - return new PixelMapElement(preparePixelmap(resource)); - } - - /** - * 根据Resource获取位图 - * - * @param resource 资源 - * @return 位图 - * @throws IOException - * @throws NotExistException - * @throws FileNotFoundException - */ - public static PixelMap preparePixelmap(Resource resource) throws IOException, NotExistException { - ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions(); - ImageSource imageSource = null; - try { - imageSource = ImageSource.create(readResource(resource), srcOpts); - } finally { - close(resource); - } - if (imageSource == null) { - throw new FileNotFoundException(); - } - ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions(); - decodingOpts.desiredSize = new Size(0, 0); - decodingOpts.desiredRegion = new ohos.media.image.common.Rect(0, 0, 0, 0); - decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888; - - PixelMap pixelmap = imageSource.createPixelmap(decodingOpts); - return pixelmap; - } - - private static void close(Resource resource) { - if (resource != null) { - try { - resource.close(); - } catch (IOException e) { - Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage()); - } - } - } - - private static byte[] readResource(Resource resource) { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - byte[] bArr = new byte[1024]; - while (true) { - try { - int read = resource.read(bArr, 0, 1024); - if (read == -1) { - break; - } - byteArrayOutputStream.write(bArr, 0, read); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } finally { - try { - byteArrayOutputStream.close(); - } catch (IOException e) { - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource failed " + e.getLocalizedMessage()); - } - } - } - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource finish"); - HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new ResUtils().getClass().getName()), "readResource len: " + byteArrayOutputStream.size()); - return byteArrayOutputStream.toByteArray(); - } - - /** - * rgb颜色值转换为rgba的ShapeElement - * - * @param rgbColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement6(int rgbColor) { - if (rgbColor < 0 && rgbColor >= -0xffffff) { - rgbColor = rgbColor + 0xffffff + 1; + public static String getPathById(Context context, int id) { + String path = ""; + if (context == null) { + return path; } - if (rgbColor > 0 && rgbColor <= 0xffffff) { - rgbColor = alphaColor(rgbColor, 1.0f); + ResourceManager manager = context.getResourceManager(); + if (manager == null) { + return path; } - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbColor)); - return shapeElement; - } - - /** - * rgb颜色值转换为rgba - * - * @param rgbColor 颜色值 - * @param alpha 透明度 - * @return int - */ - public static int alphaColor(int rgbColor, float alpha) { - if (rgbColor < 0) { - rgbColor = rgbColor + 0xffffff + 1; + try { + path = manager.getMediaPath(id); + } catch (IOException | NotExistException | WrongTypeException e) { + return path; } - int rgb = Math.max(0, rgbColor) << 8; - int al = (int) (alpha * 255); - return rgb + al; - } - - /** - * 颜色值rgba转换为ShapeElement - * - * @param rgbaColor 颜色值 - * @return ShapeElement - */ - public static ShapeElement getShapeElement8(int rgbaColor) { - ShapeElement shapeElement = new ShapeElement(); - shapeElement.setRgbColor(new RgbColor(rgbaColor)); - return shapeElement; + return path; } } diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java deleted file mode 100644 index 898266f217f2e0c75fb7528212784016618b8e60..0000000000000000000000000000000000000000 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ShapeUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain an copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.botlibre.sdk.util; - -import org.botlibre.sdk.ResourceTable; -import ohos.aafwk.ability.Ability; -import ohos.agp.components.Button; -import ohos.agp.components.Checkbox; -import ohos.agp.components.ComponentState; -import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.StateElement; -import ohos.global.resource.NotExistException; -import ohos.global.resource.Resource; - -import java.io.IOException; - -/** - * ShapeUtils - * - * @author:username - * @since 2021-05-13 - */ -public class ShapeUtils { - private ShapeUtils() { - } - - /** - * 设置button背景 - * - * @param button - * @param resId - */ - public static void setBackground(Button button, int resId) { - Resource bgResource = null; - button.setBackground(null); - try { - bgResource = button.getResourceManager().getResource(resId); - PixelMapElement pixBg = new PixelMapElement(bgResource); - button.setAroundElements(pixBg, null, null, null); - } catch (IOException | NotExistException e) { - e.getMessage(); - } - } - - /** - * 设置button背景 - * - * @param ability - * @param checkbox - */ - public static void setCheckboxBg(Ability ability, Checkbox checkbox) { - StateElement stateElement = new StateElement(); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_checked)); - stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getPixelMapDrawable(ability, - ResourceTable.Media_unchecked)); - checkbox.setButtonElement(stateElement); - } -} diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/TextStream.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/TextStream.java index 1366f761cbfb6c5971f935cf8bad0c42da1831c9..d0382e63fa3acde4e4c4fd63757c168a1f2bf0e8 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/TextStream.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/TextStream.java @@ -33,7 +33,7 @@ public class TextStream { public static final String HTTP =" \t\n\r\f\""; public static final String TOKENS =" \t\n\r\f.,:;!()?[]{}+=^&*\"`~|/\\<>"; public static final String TERMINATORS =".?!。"; - public static Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); + private static final Set ABBREVIATIONS = new HashSet(Arrays.asList(new String[]{"mr","ms", "mrs", "dr", "inc", "sr", "jr", "st"})); public static Set IGNORABLE = new HashSet(Arrays.asList(new String[]{"'","`", "\"", ","})); /** diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java index 8a7995bd5c02b4c8de8136000b4cafe7970d9b2b..d95dd3595242a802e7397a6dec6ee6883d50b30f 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/ToastUtils.java @@ -27,7 +27,6 @@ import ohos.app.Context; /** * ToastUtils * - * @author:258767-shengyu * @since 2021-04-20 */ public class ToastUtils { diff --git a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Utils.java b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Utils.java index 7faf833f8a9bc32910769222b6409f2e9b47538d..c5aecf8deba63d3f68bbc939b14e364b82c7dbee 100644 --- a/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Utils.java +++ b/SantaBot/entry/src/main/java/org/botlibre/sdk/util/Utils.java @@ -38,11 +38,11 @@ import java.util.regex.Pattern; * Utility class. */ public class Utils { - public static Random random = new Random(); + private static final Random random = new Random(); - public static Pattern httpRegex = Pattern.compile("\\b(?:https?|ftp|file):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]", Pattern.CASE_INSENSITIVE); - public static Pattern wwwRegex = Pattern.compile("((www\\.)[^\\s]+)", Pattern.CASE_INSENSITIVE); - public static Pattern emailRegex = Pattern.compile("(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+", Pattern.CASE_INSENSITIVE); + private static Pattern httpRegex = Pattern.compile("\\b(?:https?|ftp|file):\\/\\/[a-z0-9-+&@#\\/%?=~_|!:,.;]*[a-z0-9-+&@#\\/%=~_|]", Pattern.CASE_INSENSITIVE); + private static Pattern wwwRegex = Pattern.compile("((www\\.)[^\\s]+)", Pattern.CASE_INSENSITIVE); + private static Pattern emailRegex = Pattern.compile("(([a-zA-Z0-9_\\-\\.]+)@[a-zA-Z_]+?(?:\\.[a-zA-Z]{2,6}))+", Pattern.CASE_INSENSITIVE); /** * Replace links with HTML links. diff --git a/SantaBot/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java b/SantaBot/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java index 905e2e38c5c233d359f4c2af025d853f4fd6ac0e..f17d303f76316abeaf958cbdfbb672eb8074393d 100644 --- a/SantaBot/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java +++ b/SantaBot/entry/src/ohosTest/java/org/botlibre/sdk/MainAbilityTest.java @@ -27,7 +27,6 @@ import org.junit.Test; /** * 单元测试类 * - * @author BotLibre * @since 2021-05-25 */ public class MainAbilityTest { @@ -37,8 +36,6 @@ public class MainAbilityTest { @Test public void onStart() { LogUtils.d("HiLog","单元测试"); - int pxTovp = ResUtils.pxTovp(ability.getApplicationContext(),1); - Assert.assertEquals(0, pxTovp); int height = ResUtils.getScreenHeight(ability.getApplicationContext()); HiLog.info(LABEL_LOG,height + ""); int width = ResUtils.getScreenWidth(ability.getApplicationContext());