Skip to content

Instantly share code, notes, and snippets.

@SnugglePilot
Last active September 26, 2015 20:24
Show Gist options
  • Save SnugglePilot/ad1dd73706ba43700d26 to your computer and use it in GitHub Desktop.
Save SnugglePilot/ad1dd73706ba43700d26 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
public class SubmitFormOnline : MonoBehaviour {
public InputField textReference;
public string pendingDir;
// FormID comes from the google drive ID, eg:
// https://docs.google.com/forms/d/_YOURFORMID_/edit
private string formID = "_YOURFORMID_";
// fieldID comes from the published feedback form. You can pull the value from the HTML source of the form:
private const string feedbackFieldID = "entry.YOURENTRYID1";
private const string senderFieldID = "entry.YOURENTRYID2";
private const string ipID = "entry.YOURENTRYID3";
private string ip;
private bool lastError = false;
IEnumerator SendForm(string text) {
// Prevent spamming of the button when the field is empty:
if (string.IsNullOrEmpty(text)) yield break;
WWW w;
if (string.IsNullOrEmpty(ip)) {
// This fetches our external IP:
w = new WWW("https://api.ipify.org/?format=text");
yield return w;
ip = w.text;
}
WWWForm form = new WWWForm();
form.AddField(senderFieldID, "Field Notes"); // "Your Name" if you were doing the HTML entry.
form.AddField(feedbackFieldID, text);
form.AddField(ipID, ip);
string url = "https://docs.google.com/forms/d/"+formID+"/formResponse";
w = new WWW(url, form.data);
yield return w;
if (string.IsNullOrEmpty(w.error)) {
Debug.Log ("Sent feedback :)");
lastError = false;
} else {
Debug.Log ("Failed to send feedback :( Stowing for later.");
// Let's stow this feedback in a pending folder so we can retry later:
GetComponent<SaveFormToDisk>().SaveToFile(text, pendingDir);
lastError = true;
}
}
IEnumerator SendPending() {
yield return 0;
string path = FileManager.dataPath+"/"+pendingDir;
var info = new DirectoryInfo(path);
if (!info.Exists) {
// Folder doesn't exist, nothing to send.
yield break;
}
var fileInfo = info.GetFiles ();
foreach (FileInfo file in fileInfo) {
yield return StartCoroutine(SendForm (File.ReadAllText(file.FullName)));
if (lastError) {
// Failed to send, let's back out of this.
yield break;
} else {
// All was good! We can delete the file.
file.Delete ();
}
}
}
// On startup try sending previous failures.
void Start() {
StartCoroutine(SendPending());
}
// Button activation from UI:
public void Activate() {
StartCoroutine(SendForm(textReference.text));
textReference.text = "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment