Skip to content

Instantly share code, notes, and snippets.

@nicloay
Last active August 23, 2022 07:51
Show Gist options
  • Select an option

  • Save nicloay/afe42c86382445168058 to your computer and use it in GitHub Desktop.

Select an option

Save nicloay/afe42c86382445168058 to your computer and use it in GitHub Desktop.
Unity3d post vk screenshot
using UnityEngine;
/*
*
* This script created by UNITY COMUNITY and available here http://wiki.unity3d.com/index.php?title=Singleton
*
*
*/
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
private static T m_Instance = null;
public static T instance
{
get
{
// Instance requiered for the first time, we look for it
if( m_Instance == null )
{
m_Instance = GameObject.FindObjectOfType(typeof(T)) as T;
// Object not found, we create a temporary one
if( m_Instance == null )
{
Debug.LogWarning("No instance of " + typeof(T).ToString() + ", a temporary one is created.");
m_Instance = new GameObject("Temp Instance of " + typeof(T).ToString(), typeof(T)).GetComponent<T>();
// Problem during the creation, this should not happen
if( m_Instance == null )
{
Debug.LogError("Problem during the creation of " + typeof(T).ToString());
}
}
m_Instance.Init();
}
return m_Instance;
}
}
// If no other monobehaviour request the instance in an awake function
// executing before this one, no need to search the object.
private void Awake()
{
if( m_Instance == null )
{
m_Instance = this as T;
m_Instance.Init();
}
}
// This function is called when the instance is used the first time
// Put all the initializations you need here, as you would do in Awake
public virtual void Init(){}
// Make sure the instance isn't referenced anymore when the user quit, just in case.
private void OnApplicationQuit()
{
m_Instance = null;
}
}
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Specialized;
public class VKController : MonoSingleton<VKController> {
public string privateKey;
public bool initOnStart=false;
public Action<bool> onApiReady;
public NameValueCollection inputData;
CallbackPool callbackPool;
bool initialized=false;
public override void Init ()
{
Debug2.Log("init MRUController");
base.Init ();
if (initOnStart)
initializeVKApi();
}
Callback callBackOnInitDone;
Callback callbackOnInitError;
public void initializeVKApi(string key=""){
if (!String.IsNullOrEmpty(key))
privateKey = key;
if (initialized){
Debug2.LogWarning("vk api already initialized, init method will be ignored");
} else {
initialized=true;
callbackPool = CallbackPool.instance;
callbackPool.initialize();
initVKApi(privateKey,
delegate(object obj,Callback callback){
inputData = HTTPUtility.ParseQueryString ((string)obj);
Debug2.LogDebug("viewer id ="+ inputData["viewer_id"]);
callbackPool.releaseDisposableCallback(callbackOnInitError);
if (onApiReady!=null)
onApiReady(true);
Debug2.LogDebug("VK api is ready");
},
delegate(object obj,Callback callback){
onApiReady(false);
callbackPool.releaseDisposableCallback(callBackOnInitDone);
Debug2.LogError("problem with vk initialization\n"+Json.Serialize(obj));
});
}
}
public void callMethod(string methodName,params object[] parameters){
string jsParams="";
for (int i = 0; i < parameters.Length; i++) {
if (parameters[i] is string)
jsParams +=", \""+(string)parameters[i]+"\"";
else if (parameters[i] is bool)
jsParams += ", " + ((bool)parameters[i]).ToString().ToLower();
else if (parameters[i] is int)
jsParams += ", " + parameters[i];
}
string eval=@"
VK.callMethod('METHOD_NAME'PARAMETERS);
".Replace("METHOD_NAME",methodName)
.Replace("PARAMETERS",jsParams);
Debug2.LogDebug("callMethod external evaluation \n"+eval);
Application.ExternalEval(eval);
}
public void api(string methodName, object paramObject, Action<object,Callback> callback){
Callback c=callbackPool.getCallback(CallbackType.DISPOSABLE);
c.action = callback;
string eval=@"
function _callbackCALLBACK_ID(result){
callback(CALLBACK_ID, result);
}
var params=PARAMS_JSON_STRING;
VK.api(""METHOD_NAME"",params,_callbackCALLBACK_ID);
".Replace("CALLBACK_ID",""+c.id)
.Replace("METHOD_NAME",methodName)
.Replace("PARAMS_JSON_STRING",Json.Serialize(paramObject));
Debug2.LogDebug("vk.api external evaluation: \n"+eval);
Application.ExternalEval(eval);
}
void initVKApi(string key, Action<object, Callback> onInitDone, Action<object, Callback> onInitError){
callBackOnInitDone = callbackPool.getCallback(CallbackType.DISPOSABLE);
callBackOnInitDone.action = onInitDone;
callbackOnInitError = callbackPool.getCallback(CallbackType.DISPOSABLE);
callbackOnInitError.action = onInitError;
string eval=@"
function _callbackCALLBACK_ID(result){
result=location.search;
callback(CALLBACK_ID, result);
}
VK.init(function() {
_callbackCALLBACK_ID();
}, function() {
callback(CALLBACK_ON_ERROR_ID);
}, '5.1');
".Replace("CALLBACK_ID",""+callBackOnInitDone.id)
.Replace("CALLBACK_ON_ERROR_ID",""+callbackOnInitError.id);
Debug2.LogDebug("initVKApi external evaluation: \n"+eval);
Application.ExternalEval(eval);
}
public void windowConfirm(string text, Action<object, Callback> onDone){
Callback callback = callbackPool.getCallback(CallbackType.DISPOSABLE);
callback.action = onDone;
string eval=@"
var result=confirm('TEXT');
callback(CALLBACK_ID, result);
".Replace("TEXT",text.Replace("'","\"")).Replace("CALLBACK_ID",""+callback.id);
Debug2.LogDebug("windowConfirm external evaluation:\n "+eval);
Application.ExternalEval(eval);
}
public void uploadTexture(Texture2D texture, string url, string name, Action<string> callbackOnSuccess, Action<string> callbackOnError){
WWWForm form = new WWWForm();
form.AddBinaryData("photo", texture.EncodeToPNG(), name+".png", "image/png");
StartCoroutine(callbackOnWWWResponse(url,form,callbackOnSuccess,callbackOnError));
}
IEnumerator callbackOnWWWResponse(string URL, WWWForm form, Action<string> callbackOnSuccess, Action<string> callbackOnError){
WWW www = new WWW(URL, form);
yield return www;
if (www.error != null)
callbackOnError(www.error);
else
callbackOnSuccess(www.text);
www = null;
}
}
#if !UNITY_IPHONE
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using localisation;
public class VKStrategyImpl : WebStrategyInt {
bool ready = false;
VKController vkc;
string albumName="Мои раскраски в Colorus";
string albumDescription="Мои картинки из Colorus\n раскраски http://vk.com/appcolorus ";
string wallMessage="Моя новая картинка \"PICTURE_NAME\" \n раскраска Colorus http://vk.com/appcolorus ";
public void onStart (string key)
{
vkc= VKController.instance;
vkc.initializeVKApi(key);
vkc.onApiReady+=delegate(bool status){
if (status){
ready = true;
} else {
Debug2.LogError("can't initialize api");
}
};
}
public bool isReady ()
{
return ready;
}
public void onNewPictureOpen (SheetObject sheetObject)
{
string text= sheetObject.nameKey.Localized() + " | Colorus";
vkc.callMethod("setTitle",text);
}
public void onPictureSave (Texture2D texture, string pictureName)
{
vkc.api("photos.getAlbums",new Dictionary<string,object>(),delegate(object arg1, Callback arg2) {
Debug2.LogDebug("im at takeScreenshot=====\n"+Json.Serialize(arg1));
Dictionary<string,object> resultDict=arg1 as Dictionary<string,object>;
if (!resultDict.ContainsKey("response")){
Debug2.LogError("vk api error \n"+Json.Serialize(arg1));
return;
}
Dictionary<string,object> response = resultDict["response"] as Dictionary<string,object>;
List<object> items = response["items"] as List<object>;
long albumId=-1;
for (int i = 0; i < items.Count; i++) {
Dictionary<string,object> album = items[i] as Dictionary<string,object>;
if (((string)album["title"]).Equals(albumName)){
albumId =(long)album["id"];
break;
}
}
string wallText=wallMessage.Replace("PICTURE_NAME",pictureName);
if (albumId==-1)
createAlbumAndPostScreenShot(texture,wallText);
else
postScreenShot (texture, wallText, albumId);
});
}
void createAlbumAndPostScreenShot(Texture2D tex, string wallText){
Dictionary<string,object> parameters= new Dictionary<string, object>();
parameters["title"]=albumName;
parameters["description"]=albumDescription;
vkc.api("photos.createAlbum",parameters,delegate(object arg1, Callback arg2) {
Debug2.LogDebug("im at createAlbumAndPostScreenShot=====\n"+Json.Serialize(arg1));
Dictionary<string,object> resultDict=arg1 as Dictionary<string,object>;
if (!resultDict.ContainsKey("response")){
Debug2.LogError("vk api error \n"+Json.Serialize(arg1));
return;
}
Dictionary<string,object> response = resultDict["response"] as Dictionary<string,object>;
long aid=(long)response["id"];
postScreenShot(tex, wallText, aid);
});
}
void postScreenShot (Texture2D tex, string wallText, long albumId){
Dictionary<string,object> getUploadServParams=new Dictionary<string,object>();
getUploadServParams["album_id"]=(long)albumId;
vkc.api("photos.getUploadServer",getUploadServParams,delegate(object arg1, Callback arg2){
Debug2.LogDebug("im at postScreenShot getWallUploadServer=====\n"+Json.Serialize(arg1));
Dictionary<string,object> resultDict=arg1 as Dictionary<string,object>;
if (!resultDict.ContainsKey("response")){
Debug2.LogError("vk api error \n"+Json.Serialize(arg1));
return;
}
Dictionary<string,object> response = resultDict["response"] as Dictionary<string,object>;
string upload_url=(string)response["upload_url"];
vkc.uploadTexture(tex,upload_url,"colorus",
delegate(string postResult){
Debug2.LogDebug("post success \n"+postResult);
Dictionary<string,object> postResultDict=Json.Deserialize(postResult) as Dictionary<string,object>;
Dictionary<string,object> parameters=new Dictionary<string, object>();
parameters["album_id"]=albumId;
parameters["server"] = postResultDict["server"];
parameters["photos_list"] = postResultDict["photos_list"];
parameters["hash"] = postResultDict["hash"];
parameters["caption"] = "test upload to vk server";
vkc.api("photos.save",parameters,delegate(object psarg1, Callback psarg2) {
Debug2.LogDebug("im at postScreenShot getWallUploadServer=====\n"+Json.Serialize(psarg1));
Dictionary<string,object> psresultDict=psarg1 as Dictionary<string,object>;
if (!psresultDict.ContainsKey("response")){
Debug2.LogError("vk api error \n"+Json.Serialize(psarg1));
} else {
Debug2.LogDebug("photos post success \n"+Json.Serialize(psarg1));
long photoId=(long)((psresultDict["response"] as List<object>)[0] as Dictionary<string,object>)["id"];
vkc.windowConfirm("ваша картинка успешно сохранена\\n" +
"в альбоме \""+albumName+"\"\\n" +
"хотите добавить ее на стену?",delegate(object confirmObject, Callback confirmCallback) {
bool result=(bool)confirmObject;
Debug2.LogDebug("confirmation result = "+result);
if (result){
WebContext.instance.hideApplication();
Dictionary<string,object> wallProps=new Dictionary<string, object>();
wallProps["owner_id"]=vkc.inputData["viewer_id"];
wallProps["message"]=wallText;
wallProps["attachments"]="photo"+vkc.inputData["viewer_id"]+"_" + photoId;
vkc.api("wall.post",wallProps,delegate(object wallPostObj, Callback wallPostCallback) {
if (!(wallPostObj as Dictionary<string,object>).ContainsKey("response"))
Debug2.LogError("problem with wall.post upload "+ Json.Serialize(wallPostObj));
WebContext.instance.showApplication();
});
}
});
}
});
},
delegate(string postError){
Debug2.LogError("problem with post photo\n"+postError);
}
);
});
}
}
#endif
using UnityEngine;
using System.Collections;
using System;
public interface WebStrategyInt{
bool isReady();
void onStart(string data);
void onNewPictureOpen(SheetObject sheetObject);
void onPictureSave(Texture2D texture, string pictureName);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment