UnityMol  0.9.6-875
UnityMol viewer / In developement
HiRERNABackend.cs
Go to the documentation of this file.
1 /*
2  * Adapted from https://github.com/eamonwoortman/django-unity3d-example
3  */
4 
5 //using Newtonsoft.Json;
6 //using Newtonsoft.Json.Linq;
7 using System;
8 using System.Collections.Generic;
9 using System.Linq;
10 using UnityEngine;
11 using SimpleJSON;
12 using System.Text;
13 using System.IO;
14 using System.Collections;
15 using UI;
16 
17 public struct Session {
18  public int id;
19  public string name;
20  public string slug;
21 }
22 
23 public partial class BackendManager {
24  private List<Session> sessions = new List<Session>();
25  public static string progress = "";
26 
27  public Session[] getSessions()
28  {
29  return sessions.ToArray();
30  }
31 
33  public void populateSessions(JSONNode responseData)
34  {
35  sessions.Clear();
36  char[] charsToTrim = { '"' };
37  for (int i = 0; i < responseData.Count; i++)
38  {
39  Session s = new Session();
40  s.id = responseData[i]["id"].AsInt;
41  s.name = responseData[i]["name"].ToString().Trim(charsToTrim);
42  s.slug = responseData[i]["slug"].ToString().Trim(charsToTrim);
43  Debug.Log (s.slug);
44  sessions.Add(s);
45  }
46  }
47 
48  public IEnumerator downloadSessionFile(string sessionSlug)
49  {
50  Debug.Log ("Downloading molecule");
51  Dictionary<string, string> headers = new Dictionary<string, string>();
52 
53  headers.Add("Authorization", "Token " + authenticationToken);
54 
55  WWW www = new WWW(hostUrl + "sessions/" + sessionSlug + "/", null, headers);
56 
57 
58  while (!www.isDone) {
59  progress = "downloaded " + (www.progress*100).ToString() + "%...";
60  yield return null;
61  }
62 
63  string fullPath = Application.persistentDataPath + "/" + sessionSlug + ".pdb";
64  Debug.Log (fullPath);
65  File.WriteAllBytes (fullPath, www.bytes);
66 
67  Debug.Log ("Downloaded");
68 
69  progress = "downloaded, opening...";
70 
71  //clear before fetching again
73 
74  UIData.loadHireRNA = true;
75  GameObject.Find ("LoadBox").GetComponent<Molecule3D>().gUIDisplay.OpenFileCallback(fullPath);
76 
77  progress = "Done.";
78  }
79 
80  public delegate void LoggedIn();
81  public delegate void Connecting();
82  public delegate void LoginFailed(string errorMsg);
83  public LoggedIn OnLoggedIn;
84  public Connecting OnConnection;
85  public LoginFailed OnLoginFailed;
86 
87  /*
88  * Session list retrieval
89  */
90  public delegate void SessionSuccess();
91  public delegate void RetrievingSession();
92  public delegate void SessionFailed(string errorMsg);
93  public SessionSuccess OnSessionSuccess;
94  public RetrievingSession OnSession;
95  public SessionFailed OnSessionFailed;
96 
97  public delegate void SubmissionSuccess();
98  public delegate void Submitting();
99  public delegate void SubmissionFailed(string errorMsg);
100  public SubmissionSuccess OnSubmissionSuccess;
101  public Submitting OnSubmission;
102  public SubmissionFailed OnSubmissionFailed;
103 
104  private string authenticationToken = "";
105  public bool logged()
106  {
107  return authenticationToken != "";
108  }
109 
110  public void Login(string username, string password) {
111  Dictionary<string, object> fields = new Dictionary<string, object>();
112  fields.Add("username", username);
113  fields.Add("password", password);
114  if (OnConnection != null) {
115  OnConnection();
116  }
117  PerformRequest("getauthtoken/", fields, OnLoginResponse);
118  }
119 
120  private void OnLoginResponse(ResponseType responseType, JSONNode responseData, string callee) {
121  if (responseType == ResponseType.Success) {
122  authenticationToken = responseData["token"];
123  if (OnLoggedIn != null) {
124  OnLoggedIn();
125  }
126  } else {
127  if (OnLoginFailed != null) {
128  OnLoginFailed("Connection failed");
129  }
130  }
131  // } else {
132 // JToken fieldToken = responseData["non_field_errors"];
133 // if (fieldToken == null || !fieldToken.HasValues) {
134 // if (OnLoginFailed != null) {
135 // OnLoginFailed("Login failed: unknown error.");
136 // }
137 // } else {
138 // string errors = "";
139 // JToken[] fieldValidationErrors = fieldToken.Values().ToArray();
140 // foreach (JToken validationError in fieldValidationErrors) {
141 // errors += validationError.Value<string>();
142 // }
143 // if (OnLoginFailed != null) {
144 // OnLoginFailed("Login failed: " + errors);
145 // }
146 // }
147 // }
148  }
149 
150  public void Logout()
151  {
152  PerformRequest("logout/", null, OnLogoutResponse, authenticationToken);
153  }
154 
155  private void OnLogoutResponse(ResponseType responseType, JSONNode responseData, string callee)
156  {
157  authenticationToken = "";
158  sessions.Clear();
159  }
160 
161  // Take a snapshot of the current atom positions
162  public void SubmitPDB(string sessionSlug)
163  {
164  if (OnSubmission != null) {
165  OnSubmission();
166  }
167 
168  string filename = HiRERNAContestOldGUI.username + "-" + sessionSlug + "-" + DateTime.Now.ToString ("yyyyMMdd-Hmmss") +".pdb";
169 
170  string snapshot = SnapshotManager.generateSnapshot();
171 
172  WWWForm form = new WWWForm();
173  form.AddBinaryData("filename", Encoding.ASCII.GetBytes(snapshot), filename);
174 
175  PerformFormRequest("sessions/" + sessionSlug + "/submit/", form, filename, snapshot, OnSubmittedPDB, authenticationToken);
176  }
177 
178  private void OnSubmittedPDB(ResponseType responseType, JSONNode responseData, string callee)
179  {
180  if (responseType == ResponseType.Success) {
181  Debug.Log ("Success");
182  if (OnSubmissionSuccess != null) {
183  OnSubmissionSuccess();
184  }
185  } else {
186  Debug.Log ("Failure");
187  if (OnSubmissionFailed != null) {
188  OnSubmissionFailed("Submission refused");
189  }
190  }
191  }
192 
193  public void RetrieveSessions()
194  {
195  if (OnSession != null) {
196  OnSession();
197  }
198 
199  PerformRequest("sessions/", null, OnRetrievedSessions, authenticationToken);
200  }
201 
202  private void OnRetrievedSessions(ResponseType responseType, JSONNode responseData, string callee)
203  {
204  if (responseType == ResponseType.Success) {
205  populateSessions(responseData);
206  if (OnSessionSuccess != null) {
207  OnSessionSuccess();
208  }
209  } else {
210  Debug.Log ("Failure");
211  if (OnSessionFailed != null) {
212  OnSessionFailed("Session list retrieval refused");
213  }
214  }
215  }
216 }
void OnLogoutResponse(ResponseType responseType, JSONNode responseData, string callee)
void OnLoginResponse(ResponseType responseType, JSONNode responseData, string callee)
RetrievingSession OnSession
string name
override string ToString()
Definition: SimpleJSON.cs:93
static string generateSnapshot()
Produces a snapshot of the molecule in PDB format.
IEnumerator downloadSessionFile(string sessionSlug)
void OnSubmittedPDB(ResponseType responseType, JSONNode responseData, string callee)
SessionFailed OnSessionFailed
Submitting OnSubmission
SessionSuccess OnSessionSuccess
LoginFailed OnLoginFailed
Connecting OnConnection
void SubmitPDB(string sessionSlug)
static bool loadHireRNA
Definition: UIData.cs:240
Session[] getSessions()
void populateSessions(JSONNode responseData)
Populates the sessions list with received JSON data passed as argument.
string slug
SubmissionSuccess OnSubmissionSuccess
!WiP Includes FLAGS of GUI.
Definition: UIData.cs:78
void OnRetrievedSessions(ResponseType responseType, JSONNode responseData, string callee)
LoggedIn OnLoggedIn
virtual int Count
Definition: SimpleJSON.cs:71
static void clearScene()
Clears the scene.
Definition: Molecule3D.cs:156
void Login(string username, string password)
void RetrieveSessions()
virtual int AsInt
Definition: SimpleJSON.cs:106
SubmissionFailed OnSubmissionFailed
Definition: GUIDisplay.cs:66
ResponseType