public void Init(string consumer_key, string consumer_secret) { FunDebug.DebugLog1("TwitterConnector.Init called."); OnEventCallback += new EventHandler(OnEventHandler); oauth_handler_ = new OAuthHandler(consumer_key, consumer_secret); string oauth_token = PlayerPrefs.GetString("oauth_token"); string oauth_token_secret = PlayerPrefs.GetString("oauth_token_secret"); if (!string.IsNullOrEmpty(oauth_token) && !string.IsNullOrEmpty(oauth_token_secret)) { oauth_handler_.AddParameter("oauth_token", oauth_token); oauth_handler_.AddParameter("oauth_token_secret", oauth_token_secret); my_info_.id = PlayerPrefs.GetString("user_id"); my_info_.name = PlayerPrefs.GetString("screen_name"); FunDebug.Log("Logged in Twitter using saved token."); OnEventNotify(SNResultCode.kLoggedIn); } else { OnEventNotify(SNResultCode.kInitialized); } }
void downloadFileCompleteCb(object sender, System.ComponentModel.AsyncCompletedEventArgs ar) { try { if (ar.Error != null) { throw ar.Error; } image_list_.RemoveAt(0); if (image_list_.Count > 0) { KeyValuePair <string, string> item = image_list_[0]; web_client_.DownloadFileAsync(new Uri(item.Key), item.Value); FunDebug.DebugLog1("Download announcement image: {0}", item.Key); } else { FunDebug.Log("All announcement images has been downloaded.\npath:{0}", local_path_); onResult(AnnounceResult.kSucceeded); } } catch (Exception e) { FunDebug.LogError("Failure in Announcement.downloadFileCompleteCb:\n{0}", e.ToString()); onResult(AnnounceResult.kExceptionError); } }
IEnumerator RequestFriendsInfo(string ids) { oauth_handler_.Clear(); oauth_handler_.AddParameter("user_id", ids); var headers = new Dictionary <string, string>(); headers["Authorization"] = oauth_handler_.GenerateHeader(kLookupUrl, "GET"); string url = string.Format("{0}?user_id={1}", kLookupUrl, ids); WWW web = new WWW(url.ToString(), null, headers); yield return(web); if (!string.IsNullOrEmpty(web.error)) { FunDebug.LogError("Failure in RequestUserInfo: {0}", web.error); OnEventNotify(SNResultCode.kError); } else { List <object> list = Json.Deserialize(web.text) as List <object>; if (list.Count <= 0) { FunDebug.LogError("RequestUserInfo - Invalid list data. List size is 0."); yield break; } else { lock (friend_list_) { friend_list_.Clear(); foreach (Dictionary <string, object> node in list) { UserInfo user = new UserInfo(); user.id = node["id_str"] as string; user.name = node["screen_name"] as string; url = node["profile_image_url"] as string; user.url = url.Replace("_normal", "_bigger"); friend_list_.Add(user); FunDebug.DebugLog1("> id:{0} name:{1} image:{2}", user.id, user.name, user.url); } } FunDebug.Log("Succeeded in getting the friend list. count:{0}", friend_list_.Count); OnEventNotify(SNResultCode.kFriendList); lock (friend_list_) { if (auto_request_picture_ && friend_list_.Count > 0) { StartCoroutine(RequestPictures(GetFriendList())); } } } } }
void OnFriendListCb(IGraphResult result) { try { Dictionary <string, object> json = Json.Deserialize(result.RawResult) as Dictionary <string, object>; if (json == null) { FunDebug.LogError("OnFriendListCb - json is null."); OnEventNotify(SNResultCode.kError); return; } // friend list object friend_list = null; json.TryGetValue("friends", out friend_list); if (friend_list == null) { FunDebug.LogError("OnInviteListCb - friend_list is null."); OnEventNotify(SNResultCode.kError); return; } lock (friend_list_) { friend_list_.Clear(); List <object> list = ((Dictionary <string, object>)friend_list)["data"] as List <object>; foreach (object item in list) { Dictionary <string, object> info = item as Dictionary <string, object>; Dictionary <string, object> picture = ((Dictionary <string, object>)info["picture"])["data"] as Dictionary <string, object>; UserInfo user = new UserInfo(); user.id = info["id"] as string; user.name = info["name"] as string; user.url = picture["url"] as string; friend_list_.Add(user); FunDebug.DebugLog1("> id:{0} name:{1} image:{2}", user.id, user.name, user.url); } } FunDebug.Log("Succeeded in getting the friend list. count:{0}", friend_list_.Count); OnEventNotify(SNResultCode.kFriendList); lock (friend_list_) { if (auto_request_picture_ && friend_list_.Count > 0) { StartCoroutine(RequestPictures(GetFriendList())); } } } catch (Exception e) { FunDebug.LogError("Failure in OnFriendListCb: {0}", e.ToString()); } }
protected void DebugLog1(string message, params object[] args) { #if ENABLE_LOG && (LOG_LEVEL_2 || LOG_LEVEL_3) #if LOG_LEVEL_3 message = string.Format("[{0}] {1}", hash_, message); #endif FunDebug.DebugLog1(message, args); #endif }
protected IEnumerator RequestPicture(UserInfo info) { WWW www = new WWW(info.url); yield return(www); if (www.texture != null) { FunDebug.DebugLog1("{0}'s profile picture downloaded.", info.name); info.picture = www.texture; OnPictureNotify(info); } }
// Downloading files. void downloadResourceFile() { if (state_ != State.Downloading) { return; } if (download_list_.Count <= 0) { updateCachedList(); download_time_.Stop(); FunDebug.Log("Downloader took {0:F2}s for download all files.", download_time_.ElapsedMilliseconds / 1000f); state_ = State.Completed; FunDebug.Log("Downloader - Download completed."); onFinished(DownloadResult.SUCCESS); } else { DownloadFileInfo info = download_list_[0]; // Check directory string path = target_path_; int offset = info.path.LastIndexOf('/'); if (offset >= 0) { path += info.path.Substring(0, offset); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string file_path = target_path_ + info.path; if (File.Exists(file_path)) { File.Delete(file_path); } // Requests a file. string request_url = host_url_ + info.path; FunDebug.DebugLog1("Download a file - {0}\nSave to {1}\n", request_url, file_path); cur_download_path_ = Path.GetDirectoryName(file_path); cur_download_path_ += "/" + Path.GetRandomFileName(); web_client_.DownloadFileAsync(new Uri(request_url), cur_download_path_, info); } }
public void Add(string hostname, UInt16 port) { IPAddress[] list = Dns.GetHostAddresses(hostname); if (list == null) { FunDebug.LogWarning("ConnectList.Add - Can't find any ip address with '{0}' host.", hostname); return; } FunDebug.DebugLog1("[{0}] Dns address count is {1}.", hostname, list.Length); foreach (IPAddress ip in list) { addr_list_.Add(new HostIP(hostname, ip, port)); FunDebug.DebugLog1(" > {0} ({1})", ip, ip.AddressFamily); } }
void loadCachedList() { cached_list_.Clear(); string path = target_path_ + kCachedFileName; if (!File.Exists(path)) { return; } StreamReader stream = File.OpenText(path); string data = stream.ReadToEnd(); stream.Close(); if (data.Length <= 0) { FunDebug.LogWarning("Downloader.loadCachedList - Failed to load a cached file list."); return; } Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>; List <object> list = json["list"] as List <object>; foreach (Dictionary <string, object> node in list) { DownloadFileInfo info = new DownloadFileInfo(); info.path = node["path"] as string; info.size = Convert.ToUInt32(node["size"]); info.hash = node["hash"] as string; if (node.ContainsKey("front")) { info.hash_front = node["front"] as string; } else { info.hash_front = ""; } cached_list_.Add(info); } FunDebug.DebugLog1("Downloader - Loads cached list : {0}", cached_list_.Count); }
public void Init() { FunDebug.DebugLog1("FacebookConnector.Init called."); if (!FB.IsInitialized) { // Initialize the Facebook SDK FB.Init(OnInitCb, OnHideCb); } else { // Already initialized, signal an app activation App Event if (Application.isMobilePlatform) { FB.ActivateApp(); } } }
void deleteLocalFiles() { if (delete_file_list_.Count <= 0) { return; } FunDebug.Log("Downloader - Try to delete {0} local files.", delete_file_list_.Count); foreach (string path in delete_file_list_) { if (File.Exists(path)) { File.Delete(path); FunDebug.DebugLog1("'{0}' file deleted.\npath: {1}", Path.GetFileName(path), path); } } delete_file_list_.Clear(); }
void OnMyProfileCb(IGraphResult result) { FunDebug.DebugLog1("FacebookConnector.OnMyProfileCb called."); if (result.Error != null) { FunDebug.LogError(result.Error); OnEventNotify(SNResultCode.kError); return; } try { Dictionary <string, object> json = Json.Deserialize(result.RawResult) as Dictionary <string, object>; if (json == null) { FunDebug.LogError("OnMyProfileCb - json is null."); OnEventNotify(SNResultCode.kError); return; } // my profile my_info_.id = json["id"] as string; my_info_.name = json["name"] as string; FunDebug.Log("Facebook id: {0}, name: {1}.", my_info_.id, my_info_.name); // my picture var picture = json["picture"] as Dictionary <string, object>; var data = picture["data"] as Dictionary <string, object>; my_info_.url = data["url"] as string; StartCoroutine(RequestPicture(my_info_)); OnEventNotify(SNResultCode.kMyProfile); } catch (Exception e) { FunDebug.LogError("Failure in OnMyProfileCb: {0}", e.ToString()); } }
protected IEnumerator RequestPictures(List <UserInfo> list) { if (list == null || list.Count <= 0) { yield break; } foreach (UserInfo user in list) { WWW www = new WWW(user.url); yield return(www); if (www.texture != null) { FunDebug.DebugLog1("{0}'s profile picture downloaded.", user.name); user.picture = www.texture; OnPictureNotify(user); } } FunDebug.Log("The all requested profile pictures has been downloaded."); OnEventNotify(SNResultCode.kDownloadCompleted); }
void updateCachedList() { StringBuilder data = new StringBuilder(); data.Append("{ \"list\": [ "); int index = 0; foreach (DownloadFileInfo info in cached_list_) { data.AppendFormat("{{ \"path\":\"{0}\", ", info.path); data.AppendFormat("\"size\":{0}, ", info.size); if (info.hash_front.Length > 0) { data.AppendFormat("\"front\":\"{0}\", ", info.hash_front); } data.AppendFormat("\"hash\":\"{0}\" }}", info.hash); if (++index < cached_list_.Count) { data.Append(", "); } } data.Append(" ] }"); string path = target_path_ + kCachedFileName; FileStream file = File.Open(path, FileMode.Create); StreamWriter stream = new StreamWriter(file); stream.Write(data.ToString()); stream.Flush(); stream.Close(); FunDebug.DebugLog1("Downloader - Updates cached list : {0}", cached_list_.Count); }
void checkFileList(List <DownloadFileInfo> list) #endif { List <DownloadFileInfo> tmp_list = new List <DownloadFileInfo>(list); List <string> verify_file_list = new List <string>(); List <string> remove_list = new List <string>(); Queue <int> rnd_list = new Queue <int>(); bool verify_success = true; int rnd_index = -1; DateTime cached_time = File.GetLastWriteTime(target_path_ + kCachedFileName); Stopwatch elapsed_time = new Stopwatch(); elapsed_time.Start(); delete_file_list_.Clear(); // Randomly check list if (cached_list_.Count > 0) { int max_count = cached_list_.Count; int count = Math.Min(Math.Max(1, max_count / 10), 10); System.Random rnd = new System.Random((int)DateTime.Now.Ticks); while (rnd_list.Count < count) { rnd_index = rnd.Next(1, max_count + 1) - 1; if (!rnd_list.Contains(rnd_index)) { rnd_list.Enqueue(rnd_index); } } FunDebug.DebugLog1("Downloader - Random check file count is {0}", rnd_list.Count); rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1; } // Checks local files int index = 0; foreach (DownloadFileInfo file in cached_list_) { DownloadFileInfo item = list.Find(i => i.path == file.path); if (item != null) { string path = target_path_ + file.path; FileInfo info = new FileInfo(path); if (!File.Exists(path) || item.size != info.Length || item.hash != file.hash) { remove_list.Add(file.path); FunDebug.LogWarning("The file has been changed or deleted: {0}", file.path); } else { string filename = Path.GetFileName(item.path); if (filename[0] == '_' || index == rnd_index || File.GetLastWriteTime(path).Ticks > cached_time.Ticks) { if (index == rnd_index) { rnd_index = rnd_list.Count > 0 ? rnd_list.Dequeue() : -1; } verify_file_list.Add(file.path); MD5Async.Compute(mono, ref path, ref item, delegate(string p, DownloadFileInfo f, bool is_match) { if (VerifyCallback != null) { VerifyCallback(p); } verify_file_list.Remove(f.path); if (is_match) { list.Remove(f); } else { remove_list.Add(f.path); verify_success = false; } } ); } else { list.Remove(item); } } } else { remove_list.Add(file.path); } ++index; } while (verify_file_list.Count > 0) { #if !NO_UNITY yield return(new WaitForSeconds(0.1f)); #else Thread.Sleep(100); #endif } removeCachedList(remove_list); FunDebug.DebugLog1("Downloader - Random validation has {0}", (verify_success ? "succeeded" : "failed")); // Checks all local files if (!verify_success) { foreach (DownloadFileInfo file in cached_list_) { DownloadFileInfo item = tmp_list.Find(i => i.path == file.path); if (item != null) { verify_file_list.Add(file.path); string path = target_path_ + file.path; MD5Async.Compute(mono, ref path, ref item, delegate(string p, DownloadFileInfo f, bool is_match) { if (VerifyCallback != null) { VerifyCallback(p); } verify_file_list.Remove(f.path); if (!is_match) { remove_list.Add(f.path); if (!list.Contains(f)) { list.Add(f); } } } ); } } while (verify_file_list.Count > 0) { #if !NO_UNITY yield return(new WaitForSeconds(0.1f)); #else Thread.Sleep(100); #endif } removeCachedList(remove_list); } elapsed_time.Stop(); FunDebug.Log("Downloader took {0:F2}s to check local files.", elapsed_time.ElapsedMilliseconds / 1000f); total_download_count_ = list.Count; foreach (DownloadFileInfo item in list) { total_download_size_ += item.size; } if (total_download_count_ > 0) { state_ = State.Ready; event_list.Add(delegate { if (ReadyCallback != null) { ReadyCallback(total_download_count_, total_download_size_); } }); } else { deleteLocalFiles(); updateCachedList(); state_ = State.Completed; FunDebug.Log("Downloader - All resources are up to date."); onFinished(DownloadResult.SUCCESS); } }
void OnHideCb(bool isGameShown) { FunDebug.DebugLog1("isGameShown: {0}", isGameShown); }
public override void Post(string message) { FunDebug.DebugLog1("Post tweet. message: {0}", message); StartCoroutine(PostTweet(message)); }
public void Login() { FunDebug.DebugLog1("Request Twitter access token."); StartCoroutine(GetRequestToken()); }
void downloadDataCompleteCb(object sender, DownloadDataCompletedEventArgs ar) { try { if (ar.Error != null) { throw ar.Error; } // Parse json string data = Encoding.UTF8.GetString(ar.Result); Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>; if (json == null) { FunDebug.LogWarning("Announcement - Deserialize json failed. json: {0}", data); onResult(AnnounceResult.kInvalidJson); return; } FunDebug.Assert(json.ContainsKey("list")); List <object> list = json["list"] as List <object>; if (list == null || list.Count <= 0) { if (list == null) { FunDebug.LogWarning("Announcement - Announcement list is null."); } else if (list.Count <= 0) { FunDebug.LogWarning("Announcement - There is no announcement list."); } onResult(AnnounceResult.kListIsNullOrEmpty); return; } announce_list_.Clear(); foreach (Dictionary <string, object> node in list) { announce_list_.Add(node); // download image if (node.ContainsKey(kImageUrlKey) && node.ContainsKey(kImageMd5Key)) { checkDownloadImage(node[kImageUrlKey] as string, node[kImageMd5Key] as string); } } FunDebug.Log("Announcement list has been updated. total list count: {0}", announce_list_.Count); if (image_list_.Count > 0) { // Request a file. KeyValuePair <string, string> item = image_list_[0]; web_client_.DownloadFileAsync(new Uri(item.Key), item.Value); FunDebug.DebugLog1("Download announcement image: {0}", item.Key); } else { onResult(AnnounceResult.kSucceeded); } } catch (Exception e) { FunDebug.LogError("Failure in Announcement.downloadDataCompleteCb:\n{0}", e.ToString()); onResult(AnnounceResult.kExceptionError); } }