From 963e7b969730ec4ec0834d1a0600819b96f68e39 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 28 Sep 2018 17:06:55 -0400 Subject: [PATCH 01/68] Adding Tus .NET implementation and changing the .NET version to 4 to support System.Threading.Tasks --- Assets/Vimeo/Scripts/Utils/TusClient.cs | 339 ++++++++++++++++++ Assets/Vimeo/Scripts/Utils/TusClient.cs.meta | 11 + Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs | 297 +++++++++++++++ .../Vimeo/Scripts/Utils/TusHTTPClient.cs.meta | 11 + ProjectSettings/ProjectSettings.asset | 2 +- 5 files changed, 659 insertions(+), 1 deletion(-) create mode 100644 Assets/Vimeo/Scripts/Utils/TusClient.cs create mode 100644 Assets/Vimeo/Scripts/Utils/TusClient.cs.meta create mode 100644 Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs create mode 100644 Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta diff --git a/Assets/Vimeo/Scripts/Utils/TusClient.cs b/Assets/Vimeo/Scripts/Utils/TusClient.cs new file mode 100644 index 00000000..81917850 --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/TusClient.cs @@ -0,0 +1,339 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Threading; + +namespace TusClient +{ + public class TusClient + { + // *********************************************************************************************** + // Properties + + + + // *********************************************************************************************** + // Events + public delegate void UploadingEvent(long bytesTransferred, long bytesTotal); + public event UploadingEvent Uploading; + + public delegate void DownloadingEvent(long bytesTransferred, long bytesTotal); + public event DownloadingEvent Downloading; + + // *********************************************************************************************** + // Private + //------------------------------------------------------------------------------------------------ + + private CancellationTokenSource cancelSource = new CancellationTokenSource(); + + // *********************************************************************************************** + // Public + //------------------------------------------------------------------------------------------------ + + public IWebProxy Proxy { get; set; } + + public TusClient() + { + + } + + public void Cancel() + { + this.cancelSource.Cancel(); + } + + public string Create(string URL, System.IO.FileInfo file, Dictionary metadata = null) + { + if (metadata == null) + { + metadata = new Dictionary(); + } + if (!metadata.ContainsKey("filename")) + { + metadata["filename"] = file.Name; + } + return Create(URL, file.Length, metadata); + } + public string Create(string URL, long UploadLength, Dictionary metadata = null) + { + var requestUri = new Uri(URL); + var client = new TusHTTPClient(); + client.Proxy = this.Proxy; + + var request = new TusHTTPRequest(URL); + request.Method = "POST"; + request.AddHeader("Tus-Resumable", "1.0.0"); + request.AddHeader("Upload-Length", UploadLength.ToString()); + request.AddHeader("Content-Length", "0"); + + if (metadata == null) + { + metadata = new Dictionary(); + } + + var metadatastrings = new List(); + foreach (var meta in metadata) + { + string k = meta.Key.Replace(" ", "").Replace(",",""); + string v = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(meta.Value)); + metadatastrings.Add(string.Format("{0} {1}", k, v )); + } + request.AddHeader("Upload-Metadata", string.Join(",",metadatastrings.ToArray())); + + var response = client.PerformRequest(request); + + if (response.StatusCode == HttpStatusCode.Created) + { + if (response.Headers.ContainsKey("Location")) + { + Uri locationUri; + if (Uri.TryCreate(response.Headers["Location"],UriKind.RelativeOrAbsolute,out locationUri )) + { + if (!locationUri.IsAbsoluteUri) + { + locationUri = new Uri(requestUri, locationUri); + } + return locationUri.ToString(); + } + else + { + throw new Exception("Invalid Location Header"); + } + + } + else + { + throw new Exception("Location Header Missing"); + } + + } + else + { + throw new Exception("CreateFileInServer failed. " + response.ResponseString ); + } + } + //------------------------------------------------------------------------------------------------ + public void Upload(string URL, System.IO.FileInfo file) + { + using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) + { + Upload(URL, fs); + } + + } + public void Upload(string URL, System.IO.Stream fs) + { + + var Offset = this.getFileOffset(URL); + var client = new TusHTTPClient(); + System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed(); + int ChunkSize = (int) Math.Ceiling(3 * 1024.0 * 1024.0); //3 mb + + if (Offset == fs.Length) + { + if (Uploading != null) + Uploading((long)fs.Length, (long)fs.Length); + } + + + while (Offset < fs.Length) + { + fs.Seek(Offset, SeekOrigin.Begin); + byte[] buffer = new byte[ChunkSize]; + var BytesRead = fs.Read(buffer, 0, ChunkSize); + + Array.Resize(ref buffer, BytesRead); + var sha1hash = sha.ComputeHash(buffer); + + var request = new TusHTTPRequest(URL); + request.cancelToken = this.cancelSource.Token; + request.Method = "PATCH"; + request.AddHeader("Tus-Resumable", "1.0.0"); + request.AddHeader("Upload-Offset", string.Format("{0}", Offset)); + request.AddHeader("Upload-Checksum", "sha1 " + Convert.ToBase64String(sha1hash)); + request.AddHeader("Content-Type", "application/offset+octet-stream"); + request.BodyBytes = buffer; + + request.Uploading += delegate(long bytesTransferred, long bytesTotal) + { + if (Uploading != null) + Uploading((long)Offset + bytesTransferred, (long)fs.Length); + }; + + try + { + var response = client.PerformRequest(request); + + if (response.StatusCode == HttpStatusCode.NoContent) + { + Offset += BytesRead; + } + else + { + throw new Exception("WriteFileInServer failed. " + response.ResponseString); + } + } + catch (IOException ex) + { + if (ex.InnerException.GetType() == typeof(System.Net.Sockets.SocketException)) + { + var socketex = (System.Net.Sockets.SocketException) ex.InnerException; + if (socketex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset) + { + // retry by continuing the while loop but get new offset from server to prevent Conflict error + Offset = this.getFileOffset(URL); + } + else + { + throw socketex; + } + } + else + { + throw; + } + } + + + + } + + } + //------------------------------------------------------------------------------------------------ + public TusHTTPResponse Download(string URL) + { + var client = new TusHTTPClient(); + + var request = new TusHTTPRequest(URL); + request.cancelToken = this.cancelSource.Token; + request.Method = "GET"; + + request.Downloading += delegate(long bytesTransferred, long bytesTotal) + { + if (Downloading != null) + Downloading((long)bytesTransferred, (long)bytesTotal); + }; + + var response = client.PerformRequest(request); + + return response; + } + //------------------------------------------------------------------------------------------------ + public TusHTTPResponse Head(string URL) + { + var client = new TusHTTPClient(); + var request = new TusHTTPRequest(URL); + request.Method = "HEAD"; + request.AddHeader("Tus-Resumable", "1.0.0"); + + try + { + var response = client.PerformRequest(request); + return response; + } + catch (TusException ex) + { + var response = new TusHTTPResponse(); + response.StatusCode = ex.statuscode; + return response; + } + } + //------------------------------------------------------------------------------------------------ + public class TusServerInfo + { + public string Version = ""; + public string SupportedVersions = ""; + public string Extensions = ""; + public long MaxSize = 0; + + public bool SupportsDelete + { + get { return this.Extensions.Contains("termination"); } + } + + } + + public TusServerInfo getServerInfo(string URL) + { + var client = new TusHTTPClient(); + var request = new TusHTTPRequest(URL); + request.Method = "OPTIONS"; + + var response = client.PerformRequest(request); + + if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK) + { + // Spec says NoContent but tusd gives OK because of browser bugs + var info = new TusServerInfo(); + response.Headers.TryGetValue("Tus-Resumable", out info.Version); + response.Headers.TryGetValue("Tus-Version", out info.SupportedVersions); + response.Headers.TryGetValue("Tus-Extension", out info.Extensions); + + string MaxSize; + if (response.Headers.TryGetValue("Tus-Max-Size", out MaxSize)) + { + info.MaxSize = long.Parse(MaxSize); + } + else + { + info.MaxSize = 0; + } + + return info; + } + else + { + throw new Exception("getServerInfo failed. " + response.ResponseString); + } + } + //------------------------------------------------------------------------------------------------ + public bool Delete(string URL) + { + var client = new TusHTTPClient(); + var request = new TusHTTPRequest(URL); + request.Method = "DELETE"; + request.AddHeader("Tus-Resumable", "1.0.0"); + + var response = client.PerformRequest(request); + + if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone) + { + return true; + } + else + { + return false; + } + } + // *********************************************************************************************** + // Internal + //------------------------------------------------------------------------------------------------ + private long getFileOffset(string URL) + { + var client = new TusHTTPClient(); + var request = new TusHTTPRequest(URL); + request.Method = "HEAD"; + request.AddHeader("Tus-Resumable", "1.0.0"); + + var response = client.PerformRequest(request); + + if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK) + { + if (response.Headers.ContainsKey("Upload-Offset")) + { + return long.Parse(response.Headers["Upload-Offset"]); + } + else + { + throw new Exception("Offset Header Missing"); + } + } + else + { + throw new Exception("getFileOffset failed. " + response.ResponseString); + } + } + // *********************************************************************************************** + } // End of Class +} // End of Namespace \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta b/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta new file mode 100644 index 00000000..40a856fc --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46202b79a654c49ddb31b4c71352d96a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs new file mode 100644 index 00000000..f708c030 --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs @@ -0,0 +1,297 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Threading; + +namespace TusClient +{ + public class TusHTTPRequest + { + public delegate void UploadingEvent(long bytesTransferred, long bytesTotal); + public event UploadingEvent Uploading; + + public delegate void DownloadingEvent(long bytesTransferred, long bytesTotal); + public event DownloadingEvent Downloading; + + public Uri URL { get; set; } + public string Method { get; set; } + public Dictionary Headers { get; set; } + public byte[] BodyBytes { get; set; } + + public CancellationToken cancelToken; + + public string BodyText + { + get { return System.Text.Encoding.UTF8.GetString(this.BodyBytes); } + set { BodyBytes = System.Text.Encoding.UTF8.GetBytes(value); } + } + + + public TusHTTPRequest(string u) + { + this.URL = new Uri(u); + this.Method = "GET"; + this.Headers = new Dictionary(); + this.BodyBytes = new byte[0]; + } + + public void AddHeader(string k,string v) + { + this.Headers[k] = v; + } + + public void FireUploading(long bytesTransferred, long bytesTotal) + { + if (Uploading != null) + Uploading(bytesTransferred, bytesTotal); + } + + public void FireDownloading(long bytesTransferred, long bytesTotal) + { + if (Downloading != null) + Downloading(bytesTransferred, bytesTotal); + } + + } + public class TusHTTPResponse + { + public byte[] ResponseBytes { get; set; } + public string ResponseString { get { return System.Text.Encoding.UTF8.GetString(this.ResponseBytes); } } + public HttpStatusCode StatusCode { get; set; } + public Dictionary Headers { get; set; } + + public TusHTTPResponse() + { + this.Headers = new Dictionary(); + } + + } + + public class TusHTTPClient + { + + public IWebProxy Proxy { get; set; } + + + public TusHTTPResponse PerformRequest(TusHTTPRequest req) + { + + try + { + var instream = new MemoryStream(req.BodyBytes); + + HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(req.URL); + request.AutomaticDecompression = DecompressionMethods.GZip; + + request.Timeout = System.Threading.Timeout.Infinite; + request.ReadWriteTimeout = System.Threading.Timeout.Infinite; + request.Method = req.Method; + request.KeepAlive = false; + + request.Proxy = this.Proxy; + + try + { + ServicePoint currentServicePoint = request.ServicePoint; + currentServicePoint.Expect100Continue = false; + } + catch (PlatformNotSupportedException) + { + //expected on .net core 2.0 with systemproxy + //fixed by https://github.com/dotnet/corefx/commit/a9e01da6f1b3a0dfbc36d17823a2264e2ec47050 + //should work in .net core 2.2 + } + + + //SEND + req.FireUploading(0, 0); + byte[] buffer = new byte[4096]; + + long contentlength = 0; + + int byteswritten = 0; + long totalbyteswritten = 0; + + contentlength = (long)instream.Length; + request.AllowWriteStreamBuffering = false; + request.ContentLength = instream.Length; + + foreach (var header in req.Headers) + { + switch (header.Key) + { + case "Content-Length": + request.ContentLength = long.Parse(header.Value); + break; + case "Content-Type": + request.ContentType = header.Value; + break; + default: + request.Headers.Add(header.Key, header.Value); + break; + } + } + + if (req.BodyBytes.Length > 0) + { + using (System.IO.Stream requestStream = request.GetRequestStream()) + { + instream.Seek(0, SeekOrigin.Begin); + byteswritten = instream.Read(buffer, 0, buffer.Length); + + while (byteswritten > 0) + { + totalbyteswritten += byteswritten; + + req.FireUploading(totalbyteswritten, contentlength); + + requestStream.Write(buffer, 0, byteswritten); + + byteswritten = instream.Read(buffer, 0, buffer.Length); + + req.cancelToken.ThrowIfCancellationRequested(); + } + + + } + } + + req.FireDownloading(0, 0); + + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + + + contentlength = 0; + contentlength = (long)response.ContentLength; + //contentlength=0 for gzipped responses due to .net bug + + buffer = new byte[16 * 1024]; + var outstream = new MemoryStream(); + + using (Stream responseStream = response.GetResponseStream()) + { + int bytesread = 0; + long totalbytesread = 0; + + bytesread = responseStream.Read(buffer, 0, buffer.Length); + + while (bytesread > 0) + { + totalbytesread += bytesread; + + req.FireDownloading(totalbytesread, contentlength); + + outstream.Write(buffer, 0, bytesread); + + bytesread = responseStream.Read(buffer, 0, buffer.Length); + + req.cancelToken.ThrowIfCancellationRequested(); + } + } + + TusHTTPResponse resp = new TusHTTPResponse(); + resp.ResponseBytes = outstream.ToArray(); + resp.StatusCode = response.StatusCode; + foreach (string headerName in response.Headers.Keys) + { + resp.Headers[headerName] = response.Headers[headerName]; + } + + return resp; + + } + catch (OperationCanceledException cancelEx) + { + TusException rex = new TusException(cancelEx); + throw rex; + } + catch (WebException ex) + { + TusException rex = new TusException(ex); + throw rex; + } + } + } + + + public class TusException : WebException + { + + public string ResponseContent { get; set; } + public HttpStatusCode statuscode { get; set; } + public string statusdescription { get; set; } + + + public WebException OriginalException; + public TusException(TusException ex, string msg) + : base(string.Format("{0}{1}", msg, ex.Message), ex, ex.Status, ex.Response) + { + this.OriginalException = ex; + + + this.statuscode = ex.statuscode; + this.statusdescription = ex.statusdescription; + this.ResponseContent = ex.ResponseContent; + + + } + + public TusException(OperationCanceledException ex) + : base(ex.Message, ex, WebExceptionStatus.RequestCanceled, null) + { + this.OriginalException = null; + } + + public TusException(WebException ex, string msg = "") + : base(string.Format("{0}{1}", msg, ex.Message), ex, ex.Status, ex.Response) + { + + this.OriginalException = ex; + + HttpWebResponse webresp = (HttpWebResponse)ex.Response; + + + if (webresp != null) + { + this.statuscode = webresp.StatusCode; + this.statusdescription = webresp.StatusDescription; + + StreamReader readerS = new StreamReader(webresp.GetResponseStream()); + + var resp = readerS.ReadToEnd(); + + readerS.Close(); + + this.ResponseContent = resp; + } + + + } + + public string FullMessage + { + get + { + var bits = new List(); + if (this.Response != null) + { + bits.Add(string.Format("URL:{0}", this.Response.ResponseUri)); + } + bits.Add(this.Message); + if (this.statuscode != HttpStatusCode.OK) + { + bits.Add(string.Format("{0}:{1}", this.statuscode, this.statusdescription)); + } + if (!string.IsNullOrEmpty(this.ResponseContent)) + { + bits.Add(this.ResponseContent); + } + + return string.Join(Environment.NewLine, bits.ToArray()); + } + } + + } +} + diff --git a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta new file mode 100644 index 00000000..dc375f60 --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1797c6c5b7848480d8db8e44e6d73d53 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 9a40c162..c07c7852 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -559,7 +559,7 @@ PlayerSettings: incrementalIl2cppBuild: {} allowUnsafeCode: 0 additionalIl2CppArgs: - scriptingRuntimeVersion: 0 + scriptingRuntimeVersion: 1 apiCompatibilityLevelPerPlatform: {} m_RenderingPath: 1 m_MobileRenderingPath: 1 From 2af780b668a8d2c252fc0eb6c0db3ed96e224e08 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 28 Sep 2018 17:58:41 -0400 Subject: [PATCH 02/68] Adding a method to request an upload using the `TusClient()` --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index e49435b8..40c70b66 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -6,6 +6,7 @@ using UnityEngine; using UnityEngine.Networking; using SimpleJSON; +using TusClient; namespace Vimeo { @@ -250,6 +251,22 @@ IEnumerator UploadVideo(VimeoTicket ticket) } } + public void UploadVideoTus(VimeoTicket ticket) + { + + FileInfo video_file = new FileInfo(video_file_path); + + //Instance a new Tus client + TusClient.TusClient tc = new TusClient.TusClient(); + + //Prep the Tus file request + string fileURL = tc.Create(ticket.upload_link_secure, video_file); + + // Start uploading + tc.Upload(fileURL, video_file); + + } + IEnumerator VerifyUpload(VimeoTicket ticket) { if (OnUploadProgress != null) { From 4e54e8ff91401c00a9399fe9e5efbaf5e9601f55 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 3 Oct 2018 11:48:04 -0400 Subject: [PATCH 03/68] Setting up initial arch sturctue for the Vimeo Tus uploader - Created `VimeoUploader` class - Created `VideoChunk` class to represent chunks of binary video data - Tested the `Tus.io` api upload mechanisem (commented out in the `VimeoApi`) --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 57 ++- .../Vimeo/Scripts/Services/VimepUploader.cs | 139 +++++++ .../Scripts/Services/VimepUploader.cs.meta | 11 + Assets/Vimeo/Scripts/Utils/TusClient.cs | 339 ------------------ Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs | 297 --------------- 5 files changed, 191 insertions(+), 652 deletions(-) create mode 100644 Assets/Vimeo/Scripts/Services/VimepUploader.cs create mode 100644 Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta delete mode 100644 Assets/Vimeo/Scripts/Utils/TusClient.cs delete mode 100644 Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 40c70b66..25cff1eb 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -231,6 +231,47 @@ IEnumerator UploadVideo(VimeoTicket ticket) FileInfo video_file = new FileInfo(video_file_path); + //Tus upload to the Vimeo server + // string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + video_file.Length.ToString() + "\" } }"; + + // using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { + // //Prep headers + // request.chunkedTransfer = false; + // request.method = "POST"; + // request.SetRequestHeader("Authorization", "bearer " + token); + // request.SetRequestHeader("Content-Type", "application/json"); + // request.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); + + // yield return VimeoApi.SendRequest(request); + + // if(request.isNetworkError || request.isHttpError) { + // Debug.Log("[Error] " + request.error + " error code is: " + request.responseCode); + // } else { + // Debug.Log("[Vimeo] Tus ticket request complete with response code " + request.responseCode); + // JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); + // string tusUploadLink = rawJSON["upload"]["upload_link"].Value; + // Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); + + // using (UnityWebRequest uploadRequest = UnityWebRequest.Put(tusUploadLink, data)) { + // uploadRequest.chunkedTransfer = false; + // uploadRequest.method = "PATCH"; + // uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); + // uploadRequest.SetRequestHeader("Upload-Offset", "0"); + // uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + + // yield return VimeoApi.SendRequest(uploadRequest); + + // if(uploadRequest.isNetworkError || uploadRequest.isHttpError) { + // Debug.Log("[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); + // } else { + // Debug.Log("[Vimeo] Tus ticket request complete with response code " + uploadRequest.responseCode); + // Debug.Log(uploadRequest.downloadHandler.text); + // } + + // } + // } + // } + // Upload to the Vimeo server using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { uploader = request; @@ -251,22 +292,6 @@ IEnumerator UploadVideo(VimeoTicket ticket) } } - public void UploadVideoTus(VimeoTicket ticket) - { - - FileInfo video_file = new FileInfo(video_file_path); - - //Instance a new Tus client - TusClient.TusClient tc = new TusClient.TusClient(); - - //Prep the Tus file request - string fileURL = tc.Create(ticket.upload_link_secure, video_file); - - // Start uploading - tc.Upload(fileURL, video_file); - - } - IEnumerator VerifyUpload(VimeoTicket ticket) { if (OnUploadProgress != null) { diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs new file mode 100644 index 00000000..dc6ec1c3 --- /dev/null +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -0,0 +1,139 @@ +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; +using SimpleJSON; + +namespace Vimeo +{ + class VideoChunk + { + private int indexByte; + private string url; + private byte[] bytes; + public delegate void UploadEvent(string response); + public event UploadEvent OnChunckUploadComplete; + public event UploadEvent OnChunckUploadError; + + public VideoChunk(int _indexByte, string _url) + { + indexByte = _indexByte; + url = _url; + } + + private void ReadBytes() + { + + } + + private void DisposeBytes() + { + + OnChunckUploadComplete("Finished uploading chunck"); + } + + private void SendTusRequest() + { + using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) { + uploadRequest.chunkedTransfer = false; + uploadRequest.method = "PATCH"; + uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); + uploadRequest.SetRequestHeader("Upload-Offset", indexByte.ToString()); + uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + + yield return VimeoApi.SendRequest(uploadRequest); + + if(uploadRequest.isNetworkError || uploadRequest.isHttpError) { + Debug.Log("[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); + } else { + Debug.Log("[Vimeo] Tus ticket request complete with response code " + uploadRequest.responseCode); + Debug.Log(uploadRequest.downloadHandler.text); + } + + } + } + + public void Upload() + { + ReadBytes(); + SendTusRequest(); + DisposeBytes(); + + } + + } + class VimeoUploader : MonoBehaviour + { + + private List myChunks; + public int maxChunkSize; + + VimeoUploader(string file, string token) + { + + FileInfo fileInfo = new FileInfo(file); + + StartCoroutine( + Init(fileInfo, token) + ); + + } + + public IEnumerator Init(FileInfo _file_info, string _token) + { + string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + _file_info.Length.ToString() + "\" } }"; + + using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { + //Prep headers + request.chunkedTransfer = false; + request.method = "POST"; + request.SetRequestHeader("Authorization", "bearer " + _token); + request.SetRequestHeader("Content-Type", "application/json"); + request.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); + + yield return VimeoApi.SendRequest(request); + + if(request.isNetworkError || request.isHttpError) { + Debug.LogError("[Error] " + request.error + " error code is: " + request.responseCode); + } else { + + JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); + string tusUploadLink = rawJSON["upload"]["upload_link"].Value; + Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); + + //Create the chunks + float chunkFileRatio = (int)_file_info.Length / maxChunkSize; + int numChunks = (int)Mathf.Ceil(chunkFileRatio); + + for (int i = 0; i < numChunks; i++){ + + int indexByte = ((int)_file_info.Length / numChunks) * i; + VideoChunk chunk = new VideoChunk(indexByte, tusUploadLink); + chunk.OnChunckUploadComplete += OnCompleteChunk; + myChunks.Add(chunk); + + } + + } + } + + } + + public void Upload() + { + + } + + private void OnCompleteChunk(string msg) + { + + } + + private void OnChunkError(string err) + { + + } + } +} \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta b/Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta new file mode 100644 index 00000000..676edc69 --- /dev/null +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 28d9d304dbb6a49488055b6ccb0febfd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Utils/TusClient.cs b/Assets/Vimeo/Scripts/Utils/TusClient.cs deleted file mode 100644 index 81917850..00000000 --- a/Assets/Vimeo/Scripts/Utils/TusClient.cs +++ /dev/null @@ -1,339 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Threading; - -namespace TusClient -{ - public class TusClient - { - // *********************************************************************************************** - // Properties - - - - // *********************************************************************************************** - // Events - public delegate void UploadingEvent(long bytesTransferred, long bytesTotal); - public event UploadingEvent Uploading; - - public delegate void DownloadingEvent(long bytesTransferred, long bytesTotal); - public event DownloadingEvent Downloading; - - // *********************************************************************************************** - // Private - //------------------------------------------------------------------------------------------------ - - private CancellationTokenSource cancelSource = new CancellationTokenSource(); - - // *********************************************************************************************** - // Public - //------------------------------------------------------------------------------------------------ - - public IWebProxy Proxy { get; set; } - - public TusClient() - { - - } - - public void Cancel() - { - this.cancelSource.Cancel(); - } - - public string Create(string URL, System.IO.FileInfo file, Dictionary metadata = null) - { - if (metadata == null) - { - metadata = new Dictionary(); - } - if (!metadata.ContainsKey("filename")) - { - metadata["filename"] = file.Name; - } - return Create(URL, file.Length, metadata); - } - public string Create(string URL, long UploadLength, Dictionary metadata = null) - { - var requestUri = new Uri(URL); - var client = new TusHTTPClient(); - client.Proxy = this.Proxy; - - var request = new TusHTTPRequest(URL); - request.Method = "POST"; - request.AddHeader("Tus-Resumable", "1.0.0"); - request.AddHeader("Upload-Length", UploadLength.ToString()); - request.AddHeader("Content-Length", "0"); - - if (metadata == null) - { - metadata = new Dictionary(); - } - - var metadatastrings = new List(); - foreach (var meta in metadata) - { - string k = meta.Key.Replace(" ", "").Replace(",",""); - string v = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(meta.Value)); - metadatastrings.Add(string.Format("{0} {1}", k, v )); - } - request.AddHeader("Upload-Metadata", string.Join(",",metadatastrings.ToArray())); - - var response = client.PerformRequest(request); - - if (response.StatusCode == HttpStatusCode.Created) - { - if (response.Headers.ContainsKey("Location")) - { - Uri locationUri; - if (Uri.TryCreate(response.Headers["Location"],UriKind.RelativeOrAbsolute,out locationUri )) - { - if (!locationUri.IsAbsoluteUri) - { - locationUri = new Uri(requestUri, locationUri); - } - return locationUri.ToString(); - } - else - { - throw new Exception("Invalid Location Header"); - } - - } - else - { - throw new Exception("Location Header Missing"); - } - - } - else - { - throw new Exception("CreateFileInServer failed. " + response.ResponseString ); - } - } - //------------------------------------------------------------------------------------------------ - public void Upload(string URL, System.IO.FileInfo file) - { - using (var fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) - { - Upload(URL, fs); - } - - } - public void Upload(string URL, System.IO.Stream fs) - { - - var Offset = this.getFileOffset(URL); - var client = new TusHTTPClient(); - System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed(); - int ChunkSize = (int) Math.Ceiling(3 * 1024.0 * 1024.0); //3 mb - - if (Offset == fs.Length) - { - if (Uploading != null) - Uploading((long)fs.Length, (long)fs.Length); - } - - - while (Offset < fs.Length) - { - fs.Seek(Offset, SeekOrigin.Begin); - byte[] buffer = new byte[ChunkSize]; - var BytesRead = fs.Read(buffer, 0, ChunkSize); - - Array.Resize(ref buffer, BytesRead); - var sha1hash = sha.ComputeHash(buffer); - - var request = new TusHTTPRequest(URL); - request.cancelToken = this.cancelSource.Token; - request.Method = "PATCH"; - request.AddHeader("Tus-Resumable", "1.0.0"); - request.AddHeader("Upload-Offset", string.Format("{0}", Offset)); - request.AddHeader("Upload-Checksum", "sha1 " + Convert.ToBase64String(sha1hash)); - request.AddHeader("Content-Type", "application/offset+octet-stream"); - request.BodyBytes = buffer; - - request.Uploading += delegate(long bytesTransferred, long bytesTotal) - { - if (Uploading != null) - Uploading((long)Offset + bytesTransferred, (long)fs.Length); - }; - - try - { - var response = client.PerformRequest(request); - - if (response.StatusCode == HttpStatusCode.NoContent) - { - Offset += BytesRead; - } - else - { - throw new Exception("WriteFileInServer failed. " + response.ResponseString); - } - } - catch (IOException ex) - { - if (ex.InnerException.GetType() == typeof(System.Net.Sockets.SocketException)) - { - var socketex = (System.Net.Sockets.SocketException) ex.InnerException; - if (socketex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset) - { - // retry by continuing the while loop but get new offset from server to prevent Conflict error - Offset = this.getFileOffset(URL); - } - else - { - throw socketex; - } - } - else - { - throw; - } - } - - - - } - - } - //------------------------------------------------------------------------------------------------ - public TusHTTPResponse Download(string URL) - { - var client = new TusHTTPClient(); - - var request = new TusHTTPRequest(URL); - request.cancelToken = this.cancelSource.Token; - request.Method = "GET"; - - request.Downloading += delegate(long bytesTransferred, long bytesTotal) - { - if (Downloading != null) - Downloading((long)bytesTransferred, (long)bytesTotal); - }; - - var response = client.PerformRequest(request); - - return response; - } - //------------------------------------------------------------------------------------------------ - public TusHTTPResponse Head(string URL) - { - var client = new TusHTTPClient(); - var request = new TusHTTPRequest(URL); - request.Method = "HEAD"; - request.AddHeader("Tus-Resumable", "1.0.0"); - - try - { - var response = client.PerformRequest(request); - return response; - } - catch (TusException ex) - { - var response = new TusHTTPResponse(); - response.StatusCode = ex.statuscode; - return response; - } - } - //------------------------------------------------------------------------------------------------ - public class TusServerInfo - { - public string Version = ""; - public string SupportedVersions = ""; - public string Extensions = ""; - public long MaxSize = 0; - - public bool SupportsDelete - { - get { return this.Extensions.Contains("termination"); } - } - - } - - public TusServerInfo getServerInfo(string URL) - { - var client = new TusHTTPClient(); - var request = new TusHTTPRequest(URL); - request.Method = "OPTIONS"; - - var response = client.PerformRequest(request); - - if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK) - { - // Spec says NoContent but tusd gives OK because of browser bugs - var info = new TusServerInfo(); - response.Headers.TryGetValue("Tus-Resumable", out info.Version); - response.Headers.TryGetValue("Tus-Version", out info.SupportedVersions); - response.Headers.TryGetValue("Tus-Extension", out info.Extensions); - - string MaxSize; - if (response.Headers.TryGetValue("Tus-Max-Size", out MaxSize)) - { - info.MaxSize = long.Parse(MaxSize); - } - else - { - info.MaxSize = 0; - } - - return info; - } - else - { - throw new Exception("getServerInfo failed. " + response.ResponseString); - } - } - //------------------------------------------------------------------------------------------------ - public bool Delete(string URL) - { - var client = new TusHTTPClient(); - var request = new TusHTTPRequest(URL); - request.Method = "DELETE"; - request.AddHeader("Tus-Resumable", "1.0.0"); - - var response = client.PerformRequest(request); - - if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone) - { - return true; - } - else - { - return false; - } - } - // *********************************************************************************************** - // Internal - //------------------------------------------------------------------------------------------------ - private long getFileOffset(string URL) - { - var client = new TusHTTPClient(); - var request = new TusHTTPRequest(URL); - request.Method = "HEAD"; - request.AddHeader("Tus-Resumable", "1.0.0"); - - var response = client.PerformRequest(request); - - if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK) - { - if (response.Headers.ContainsKey("Upload-Offset")) - { - return long.Parse(response.Headers["Upload-Offset"]); - } - else - { - throw new Exception("Offset Header Missing"); - } - } - else - { - throw new Exception("getFileOffset failed. " + response.ResponseString); - } - } - // *********************************************************************************************** - } // End of Class -} // End of Namespace \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs deleted file mode 100644 index f708c030..00000000 --- a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs +++ /dev/null @@ -1,297 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Threading; - -namespace TusClient -{ - public class TusHTTPRequest - { - public delegate void UploadingEvent(long bytesTransferred, long bytesTotal); - public event UploadingEvent Uploading; - - public delegate void DownloadingEvent(long bytesTransferred, long bytesTotal); - public event DownloadingEvent Downloading; - - public Uri URL { get; set; } - public string Method { get; set; } - public Dictionary Headers { get; set; } - public byte[] BodyBytes { get; set; } - - public CancellationToken cancelToken; - - public string BodyText - { - get { return System.Text.Encoding.UTF8.GetString(this.BodyBytes); } - set { BodyBytes = System.Text.Encoding.UTF8.GetBytes(value); } - } - - - public TusHTTPRequest(string u) - { - this.URL = new Uri(u); - this.Method = "GET"; - this.Headers = new Dictionary(); - this.BodyBytes = new byte[0]; - } - - public void AddHeader(string k,string v) - { - this.Headers[k] = v; - } - - public void FireUploading(long bytesTransferred, long bytesTotal) - { - if (Uploading != null) - Uploading(bytesTransferred, bytesTotal); - } - - public void FireDownloading(long bytesTransferred, long bytesTotal) - { - if (Downloading != null) - Downloading(bytesTransferred, bytesTotal); - } - - } - public class TusHTTPResponse - { - public byte[] ResponseBytes { get; set; } - public string ResponseString { get { return System.Text.Encoding.UTF8.GetString(this.ResponseBytes); } } - public HttpStatusCode StatusCode { get; set; } - public Dictionary Headers { get; set; } - - public TusHTTPResponse() - { - this.Headers = new Dictionary(); - } - - } - - public class TusHTTPClient - { - - public IWebProxy Proxy { get; set; } - - - public TusHTTPResponse PerformRequest(TusHTTPRequest req) - { - - try - { - var instream = new MemoryStream(req.BodyBytes); - - HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(req.URL); - request.AutomaticDecompression = DecompressionMethods.GZip; - - request.Timeout = System.Threading.Timeout.Infinite; - request.ReadWriteTimeout = System.Threading.Timeout.Infinite; - request.Method = req.Method; - request.KeepAlive = false; - - request.Proxy = this.Proxy; - - try - { - ServicePoint currentServicePoint = request.ServicePoint; - currentServicePoint.Expect100Continue = false; - } - catch (PlatformNotSupportedException) - { - //expected on .net core 2.0 with systemproxy - //fixed by https://github.com/dotnet/corefx/commit/a9e01da6f1b3a0dfbc36d17823a2264e2ec47050 - //should work in .net core 2.2 - } - - - //SEND - req.FireUploading(0, 0); - byte[] buffer = new byte[4096]; - - long contentlength = 0; - - int byteswritten = 0; - long totalbyteswritten = 0; - - contentlength = (long)instream.Length; - request.AllowWriteStreamBuffering = false; - request.ContentLength = instream.Length; - - foreach (var header in req.Headers) - { - switch (header.Key) - { - case "Content-Length": - request.ContentLength = long.Parse(header.Value); - break; - case "Content-Type": - request.ContentType = header.Value; - break; - default: - request.Headers.Add(header.Key, header.Value); - break; - } - } - - if (req.BodyBytes.Length > 0) - { - using (System.IO.Stream requestStream = request.GetRequestStream()) - { - instream.Seek(0, SeekOrigin.Begin); - byteswritten = instream.Read(buffer, 0, buffer.Length); - - while (byteswritten > 0) - { - totalbyteswritten += byteswritten; - - req.FireUploading(totalbyteswritten, contentlength); - - requestStream.Write(buffer, 0, byteswritten); - - byteswritten = instream.Read(buffer, 0, buffer.Length); - - req.cancelToken.ThrowIfCancellationRequested(); - } - - - } - } - - req.FireDownloading(0, 0); - - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); - - - contentlength = 0; - contentlength = (long)response.ContentLength; - //contentlength=0 for gzipped responses due to .net bug - - buffer = new byte[16 * 1024]; - var outstream = new MemoryStream(); - - using (Stream responseStream = response.GetResponseStream()) - { - int bytesread = 0; - long totalbytesread = 0; - - bytesread = responseStream.Read(buffer, 0, buffer.Length); - - while (bytesread > 0) - { - totalbytesread += bytesread; - - req.FireDownloading(totalbytesread, contentlength); - - outstream.Write(buffer, 0, bytesread); - - bytesread = responseStream.Read(buffer, 0, buffer.Length); - - req.cancelToken.ThrowIfCancellationRequested(); - } - } - - TusHTTPResponse resp = new TusHTTPResponse(); - resp.ResponseBytes = outstream.ToArray(); - resp.StatusCode = response.StatusCode; - foreach (string headerName in response.Headers.Keys) - { - resp.Headers[headerName] = response.Headers[headerName]; - } - - return resp; - - } - catch (OperationCanceledException cancelEx) - { - TusException rex = new TusException(cancelEx); - throw rex; - } - catch (WebException ex) - { - TusException rex = new TusException(ex); - throw rex; - } - } - } - - - public class TusException : WebException - { - - public string ResponseContent { get; set; } - public HttpStatusCode statuscode { get; set; } - public string statusdescription { get; set; } - - - public WebException OriginalException; - public TusException(TusException ex, string msg) - : base(string.Format("{0}{1}", msg, ex.Message), ex, ex.Status, ex.Response) - { - this.OriginalException = ex; - - - this.statuscode = ex.statuscode; - this.statusdescription = ex.statusdescription; - this.ResponseContent = ex.ResponseContent; - - - } - - public TusException(OperationCanceledException ex) - : base(ex.Message, ex, WebExceptionStatus.RequestCanceled, null) - { - this.OriginalException = null; - } - - public TusException(WebException ex, string msg = "") - : base(string.Format("{0}{1}", msg, ex.Message), ex, ex.Status, ex.Response) - { - - this.OriginalException = ex; - - HttpWebResponse webresp = (HttpWebResponse)ex.Response; - - - if (webresp != null) - { - this.statuscode = webresp.StatusCode; - this.statusdescription = webresp.StatusDescription; - - StreamReader readerS = new StreamReader(webresp.GetResponseStream()); - - var resp = readerS.ReadToEnd(); - - readerS.Close(); - - this.ResponseContent = resp; - } - - - } - - public string FullMessage - { - get - { - var bits = new List(); - if (this.Response != null) - { - bits.Add(string.Format("URL:{0}", this.Response.ResponseUri)); - } - bits.Add(this.Message); - if (this.statuscode != HttpStatusCode.OK) - { - bits.Add(string.Format("{0}:{1}", this.statuscode, this.statusdescription)); - } - if (!string.IsNullOrEmpty(this.ResponseContent)) - { - bits.Add(this.ResponseContent); - } - - return string.Join(Environment.NewLine, bits.ToArray()); - } - } - - } -} - From 0705197b9e5371ad5d18af460b360b7bbbe7cf42 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 3 Oct 2018 15:09:33 -0400 Subject: [PATCH 04/68] Improving VideoChunk class and finishing byte reading --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 3 +- .../Vimeo/Scripts/Services/VimepUploader.cs | 50 +++++++++++++------ Assets/Vimeo/Scripts/Utils/TusClient.cs.meta | 11 ---- .../Vimeo/Scripts/Utils/TusHTTPClient.cs.meta | 11 ---- 4 files changed, 35 insertions(+), 40 deletions(-) delete mode 100644 Assets/Vimeo/Scripts/Utils/TusClient.cs.meta delete mode 100644 Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 25cff1eb..590d573b 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -6,7 +6,6 @@ using UnityEngine; using UnityEngine.Networking; using SimpleJSON; -using TusClient; namespace Vimeo { @@ -271,7 +270,7 @@ IEnumerator UploadVideo(VimeoTicket ticket) // } // } // } - + // Upload to the Vimeo server using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { uploader = request; diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index dc6ec1c3..b82a3eb5 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -1,4 +1,5 @@ using System.IO; +using System; using System.Collections; using System.Collections.Generic; using System.Text; @@ -8,34 +9,40 @@ namespace Vimeo { - class VideoChunk + class VideoChunk : MonoBehaviour { private int indexByte; private string url; private byte[] bytes; + private int chuckSize; public delegate void UploadEvent(string response); public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; - public VideoChunk(int _indexByte, string _url) + public VideoChunk(int _indexByte, string _url, int _chucnkSize) { + bytes = new byte[_chucnkSize]; indexByte = _indexByte; url = _url; } private void ReadBytes() { - + using (BinaryReader reader = new BinaryReader(new FileStream(url, FileMode.Open))) { + reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); + reader.Read(bytes, 0, bytes.Length); + } } private void DisposeBytes() { - + Array.Clear(bytes, 0, bytes.Length); OnChunckUploadComplete("Finished uploading chunck"); } - private void SendTusRequest() + private IEnumerator SendTusRequest() { + ReadBytes(); using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) { uploadRequest.chunkedTransfer = false; uploadRequest.method = "PATCH"; @@ -49,28 +56,25 @@ private void SendTusRequest() Debug.Log("[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); } else { Debug.Log("[Vimeo] Tus ticket request complete with response code " + uploadRequest.responseCode); - Debug.Log(uploadRequest.downloadHandler.text); + Debug.Log(uploadRequest.downloadHandler.text); } - } + DisposeBytes(); } public void Upload() { - ReadBytes(); - SendTusRequest(); - DisposeBytes(); - + StartCoroutine(SendTusRequest()); } } class VimeoUploader : MonoBehaviour { - private List myChunks; + private Queue myChunks; public int maxChunkSize; - VimeoUploader(string file, string token) + public VimeoUploader(string file, string token) { FileInfo fileInfo = new FileInfo(file); @@ -96,7 +100,7 @@ public IEnumerator Init(FileInfo _file_info, string _token) yield return VimeoApi.SendRequest(request); if(request.isNetworkError || request.isHttpError) { - Debug.LogError("[Error] " + request.error + " error code is: " + request.responseCode); + OnError("[Error] " + request.error + " error code is: " + request.responseCode); } else { JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); @@ -110,9 +114,13 @@ public IEnumerator Init(FileInfo _file_info, string _token) for (int i = 0; i < numChunks; i++){ int indexByte = ((int)_file_info.Length / numChunks) * i; - VideoChunk chunk = new VideoChunk(indexByte, tusUploadLink); + VideoChunk chunk = new VideoChunk(indexByte, tusUploadLink, maxChunkSize); + + //Register evenets chunk.OnChunckUploadComplete += OnCompleteChunk; - myChunks.Add(chunk); + + //Push it to the queue + myChunks.Enqueue(chunk); } @@ -121,6 +129,11 @@ public IEnumerator Init(FileInfo _file_info, string _token) } + public void SetChunkSize(int size) + { + maxChunkSize = size; + } + public void Upload() { @@ -135,5 +148,10 @@ private void OnChunkError(string err) { } + + private void OnError(string err) + { + + } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta b/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta deleted file mode 100644 index 40a856fc..00000000 --- a/Assets/Vimeo/Scripts/Utils/TusClient.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 46202b79a654c49ddb31b4c71352d96a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta b/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta deleted file mode 100644 index dc375f60..00000000 --- a/Assets/Vimeo/Scripts/Utils/TusHTTPClient.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 1797c6c5b7848480d8db8e44e6d73d53 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 4064cb7a0a05835e32ee76f2321ddcdf8bd45647 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 3 Oct 2018 15:30:20 -0400 Subject: [PATCH 05/68] =?UTF-8?q?Calling=20the=20VimeoUploader=20from=20th?= =?UTF-8?q?e=20VimeoApi=20class=20-=20and=20it=20works=20=F0=9F=A4=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 2 ++ Assets/Vimeo/Scripts/Services/VimepUploader.cs | 17 ++++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 590d573b..3f980547 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -270,6 +270,8 @@ IEnumerator UploadVideo(VimeoTicket ticket) // } // } // } + VimeoUploader tus_uploader = this.gameObject.AddComponent(); + tus_uploader.Init(video_file_path, token); // Upload to the Vimeo server using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index b82a3eb5..2e9c7be3 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -19,7 +19,7 @@ class VideoChunk : MonoBehaviour public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; - public VideoChunk(int _indexByte, string _url, int _chucnkSize) + public void Init(int _indexByte, string _url, int _chucnkSize) { bytes = new byte[_chucnkSize]; indexByte = _indexByte; @@ -73,16 +73,18 @@ class VimeoUploader : MonoBehaviour private Queue myChunks; public int maxChunkSize; - - public VimeoUploader(string file, string token) - { + public void Init(string file, string token) + { + myChunks = new Queue(); + FileInfo fileInfo = new FileInfo(file); + maxChunkSize = 10000; + StartCoroutine( Init(fileInfo, token) ); - } public IEnumerator Init(FileInfo _file_info, string _token) @@ -106,7 +108,7 @@ public IEnumerator Init(FileInfo _file_info, string _token) JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); string tusUploadLink = rawJSON["upload"]["upload_link"].Value; Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); - + //Create the chunks float chunkFileRatio = (int)_file_info.Length / maxChunkSize; int numChunks = (int)Mathf.Ceil(chunkFileRatio); @@ -114,7 +116,8 @@ public IEnumerator Init(FileInfo _file_info, string _token) for (int i = 0; i < numChunks; i++){ int indexByte = ((int)_file_info.Length / numChunks) * i; - VideoChunk chunk = new VideoChunk(indexByte, tusUploadLink, maxChunkSize); + VideoChunk chunk = this.gameObject.AddComponent(); + chunk.Init(indexByte, tusUploadLink, maxChunkSize); //Register evenets chunk.OnChunckUploadComplete += OnCompleteChunk; From 9cff299db3bffb7ac57afd9405cf759f46980854 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 4 Oct 2018 14:02:20 -0400 Subject: [PATCH 06/68] Making the VimeoUploader upload videos using the Vimeo tus API --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 33 ++++---- .../Vimeo/Scripts/Services/VimepUploader.cs | 79 +++++++++++-------- 2 files changed, 65 insertions(+), 47 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 3f980547..a0828d40 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -271,26 +271,27 @@ IEnumerator UploadVideo(VimeoTicket ticket) // } // } VimeoUploader tus_uploader = this.gameObject.AddComponent(); - tus_uploader.Init(video_file_path, token); + yield return tus_uploader.Init(video_file_path, token); + tus_uploader.Upload(); // Upload to the Vimeo server - using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { - uploader = request; - request.chunkedTransfer = false; - request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); - yield return VimeoApi.SendRequest(request); + // using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { + // uploader = request; + // request.chunkedTransfer = false; + // request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); + // yield return VimeoApi.SendRequest(request); - uploader = null; + // uploader = null; - if (IsNetworkError(request)) { - if (OnNetworkError != null) { - OnNetworkError(request.error); - } - } - else { - StartCoroutine(VerifyUpload(ticket)); - } - } + // if (IsNetworkError(request)) { + // if (OnNetworkError != null) { + // OnNetworkError(request.error); + // } + // } + // else { + // StartCoroutine(VerifyUpload(ticket)); + // } + // } } IEnumerator VerifyUpload(VimeoTicket ticket) diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index 2e9c7be3..a126d835 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -7,6 +7,14 @@ using UnityEngine.Networking; using SimpleJSON; +/* + TODO: + - Format the whole code + - Get rid of unused namespaces + - Split functionality into seprate methods + - Split VideoChunk and VimeoUploader to seprate files +*/ + namespace Vimeo { class VideoChunk : MonoBehaviour @@ -14,21 +22,24 @@ class VideoChunk : MonoBehaviour private int indexByte; private string url; private byte[] bytes; + private string file_path; private int chuckSize; - public delegate void UploadEvent(string response); + + public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; - public void Init(int _indexByte, string _url, int _chucnkSize) + public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize) { bytes = new byte[_chucnkSize]; + file_path = _file_path; indexByte = _indexByte; url = _url; } private void ReadBytes() { - using (BinaryReader reader = new BinaryReader(new FileStream(url, FileMode.Open))) { + using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open))) { reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } @@ -37,7 +48,6 @@ private void ReadBytes() private void DisposeBytes() { Array.Clear(bytes, 0, bytes.Length); - OnChunckUploadComplete("Finished uploading chunck"); } private IEnumerator SendTusRequest() @@ -47,16 +57,16 @@ private IEnumerator SendTusRequest() uploadRequest.chunkedTransfer = false; uploadRequest.method = "PATCH"; uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", indexByte.ToString()); + uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); yield return VimeoApi.SendRequest(uploadRequest); if(uploadRequest.isNetworkError || uploadRequest.isHttpError) { - Debug.Log("[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); + string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; + OnChunckUploadError(this, concatErr); } else { - Debug.Log("[Vimeo] Tus ticket request complete with response code " + uploadRequest.responseCode); - Debug.Log(uploadRequest.downloadHandler.text); + OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); } } DisposeBytes(); @@ -74,22 +84,15 @@ class VimeoUploader : MonoBehaviour private Queue myChunks; public int maxChunkSize; - public void Init(string file, string token) + public IEnumerator Init(string _file, string _token) { myChunks = new Queue(); - - FileInfo fileInfo = new FileInfo(file); - + maxChunkSize = 10000; - StartCoroutine( - Init(fileInfo, token) - ); - } + FileInfo fileInfo = new FileInfo(_file); - public IEnumerator Init(FileInfo _file_info, string _token) - { - string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + _file_info.Length.ToString() + "\" } }"; + string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileInfo.Length.ToString() + "\" } }"; using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { //Prep headers @@ -110,18 +113,25 @@ public IEnumerator Init(FileInfo _file_info, string _token) Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); //Create the chunks - float chunkFileRatio = (int)_file_info.Length / maxChunkSize; - int numChunks = (int)Mathf.Ceil(chunkFileRatio); - + int numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); + Debug.Log("Number of chunks is " + numChunks + " and file size is " + fileInfo.Length.ToString()); for (int i = 0; i < numChunks; i++){ - - int indexByte = ((int)_file_info.Length / numChunks) * i; + int indexByte = maxChunkSize * i; VideoChunk chunk = this.gameObject.AddComponent(); - chunk.Init(indexByte, tusUploadLink, maxChunkSize); + //If we are at the last chunk set the max chunk size to the fractional remainder + if (i + 1 == numChunks) { + int remainder = (int)fileInfo.Length - (maxChunkSize * i); + Debug.Log("Created last chunk and the remainder is: " + remainder); + chunk.Init(indexByte, tusUploadLink, _file, remainder); + } else { + chunk.Init(indexByte, tusUploadLink, _file, maxChunkSize); + } + //Register evenets chunk.OnChunckUploadComplete += OnCompleteChunk; - + chunk.OnChunckUploadError += OnChunkError; + //Push it to the queue myChunks.Enqueue(chunk); @@ -138,16 +148,23 @@ public void SetChunkSize(int size) } public void Upload() - { - + { + //Kick off the first chunk, currently will call other chunks via the OnCompleteChunk event + VideoChunk firstChunk = myChunks.Dequeue(); + firstChunk.Upload(); } - private void OnCompleteChunk(string msg) + private void OnCompleteChunk(VideoChunk chunk, string msg) { - + Debug.Log(myChunks.Count); + //Make sure the queue is not empty + if (myChunks.Count != 0) { + VideoChunk nextChunk = myChunks.Dequeue(); + nextChunk.Upload(); + } } - private void OnChunkError(string err) + private void OnChunkError(VideoChunk chunk, string err) { } From f386cda25d6b88181335c934be2f7b19945e3e1b Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 4 Oct 2018 17:00:59 -0400 Subject: [PATCH 07/68] Testing long recording and implementing more events --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 68 +++----------- .../Vimeo/Scripts/Services/VimepUploader.cs | 93 ++++++++++++------- 2 files changed, 72 insertions(+), 89 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index a0828d40..60c134cd 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -211,65 +211,25 @@ IEnumerator UploadVideo(VimeoTicket ticket) OnUploadProgress("Uploading", 0); } - byte[] data = new byte[0]; - bool success = false; + // byte[] data = new byte[0]; + // bool success = false; // Using try/catch to wait for video to finish being - while (success == false) { - try { - // Get local video file and store it in a byte array for uploading - data = File.ReadAllBytes(video_file_path); - success = true; - } - catch (IOException e) { - // TODO: fix this ugly code! - Debug.Log("File is being accessed by another process. " + e.Message); - } - } - - FileInfo video_file = new FileInfo(video_file_path); - - //Tus upload to the Vimeo server - // string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + video_file.Length.ToString() + "\" } }"; - - // using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { - // //Prep headers - // request.chunkedTransfer = false; - // request.method = "POST"; - // request.SetRequestHeader("Authorization", "bearer " + token); - // request.SetRequestHeader("Content-Type", "application/json"); - // request.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); - - // yield return VimeoApi.SendRequest(request); - - // if(request.isNetworkError || request.isHttpError) { - // Debug.Log("[Error] " + request.error + " error code is: " + request.responseCode); - // } else { - // Debug.Log("[Vimeo] Tus ticket request complete with response code " + request.responseCode); - // JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); - // string tusUploadLink = rawJSON["upload"]["upload_link"].Value; - // Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); - - // using (UnityWebRequest uploadRequest = UnityWebRequest.Put(tusUploadLink, data)) { - // uploadRequest.chunkedTransfer = false; - // uploadRequest.method = "PATCH"; - // uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - // uploadRequest.SetRequestHeader("Upload-Offset", "0"); - // uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); - - // yield return VimeoApi.SendRequest(uploadRequest); - - // if(uploadRequest.isNetworkError || uploadRequest.isHttpError) { - // Debug.Log("[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); - // } else { - // Debug.Log("[Vimeo] Tus ticket request complete with response code " + uploadRequest.responseCode); - // Debug.Log(uploadRequest.downloadHandler.text); - // } - - // } + // while (success == false) { + // try { + // // Get local video file and store it in a byte array for uploading + // data = File.ReadAllBytes(video_file_path); + // success = true; + // } + // catch (IOException e) { + // // TODO: fix this ugly code! + // Debug.Log("File is being accessed by another process. " + e.Message); // } // } + + // FileInfo video_file = new FileInfo(video_file_path); + VimeoUploader tus_uploader = this.gameObject.AddComponent(); yield return tus_uploader.Init(video_file_path, token); tus_uploader.Upload(); diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index a126d835..b7203b03 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -15,7 +15,7 @@ - Split VideoChunk and VimeoUploader to seprate files */ -namespace Vimeo +namespace Vimeo { class VideoChunk : MonoBehaviour { @@ -24,7 +24,7 @@ class VideoChunk : MonoBehaviour private byte[] bytes; private string file_path; private int chuckSize; - + public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; @@ -39,7 +39,8 @@ public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize private void ReadBytes() { - using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open))) { + using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) + { reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } @@ -53,21 +54,25 @@ private void DisposeBytes() private IEnumerator SendTusRequest() { ReadBytes(); - using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) { - uploadRequest.chunkedTransfer = false; - uploadRequest.method = "PATCH"; - uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); - uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); - - yield return VimeoApi.SendRequest(uploadRequest); - - if(uploadRequest.isNetworkError || uploadRequest.isHttpError) { - string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; - OnChunckUploadError(this, concatErr); - } else { - OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); - } + using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) + { + uploadRequest.chunkedTransfer = false; + uploadRequest.method = "PATCH"; + uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); + uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); + uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + + yield return VimeoApi.SendRequest(uploadRequest); + + if (uploadRequest.isNetworkError || uploadRequest.isHttpError) + { + string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; + OnChunckUploadError(this, concatErr); + } + else + { + OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); + } } DisposeBytes(); } @@ -80,21 +85,25 @@ public void Upload() } class VimeoUploader : MonoBehaviour { - + public delegate void UploadAction(string status, float progress = 0.0f); + public event UploadAction OnUploadProgress; private Queue myChunks; + private int numChunks; public int maxChunkSize; - - public IEnumerator Init(string _file, string _token) + public IEnumerator Init(string _file, string _token, int _maxChunkSize = 1000) { myChunks = new Queue(); - maxChunkSize = 10000; + maxChunkSize = _maxChunkSize; FileInfo fileInfo = new FileInfo(_file); + Debug.Log("File size in bytes" + fileInfo.Length.ToString()); + string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileInfo.Length.ToString() + "\" } }"; - using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { + using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) + { //Prep headers request.chunkedTransfer = false; request.method = "POST"; @@ -104,30 +113,38 @@ public IEnumerator Init(string _file, string _token) yield return VimeoApi.SendRequest(request); - if(request.isNetworkError || request.isHttpError) { + Debug.Log("After request"); + if (request.isNetworkError || request.isHttpError) + { OnError("[Error] " + request.error + " error code is: " + request.responseCode); - } else { + } + else + { JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); string tusUploadLink = rawJSON["upload"]["upload_link"].Value; Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); //Create the chunks - int numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); + numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); Debug.Log("Number of chunks is " + numChunks + " and file size is " + fileInfo.Length.ToString()); - for (int i = 0; i < numChunks; i++){ + for (int i = 0; i < numChunks; i++) + { int indexByte = maxChunkSize * i; VideoChunk chunk = this.gameObject.AddComponent(); //If we are at the last chunk set the max chunk size to the fractional remainder - if (i + 1 == numChunks) { + if (i + 1 == numChunks) + { int remainder = (int)fileInfo.Length - (maxChunkSize * i); Debug.Log("Created last chunk and the remainder is: " + remainder); chunk.Init(indexByte, tusUploadLink, _file, remainder); - } else { + } + else + { chunk.Init(indexByte, tusUploadLink, _file, maxChunkSize); } - + //Register evenets chunk.OnChunckUploadComplete += OnCompleteChunk; chunk.OnChunckUploadError += OnChunkError; @@ -148,7 +165,7 @@ public void SetChunkSize(int size) } public void Upload() - { + { //Kick off the first chunk, currently will call other chunks via the OnCompleteChunk event VideoChunk firstChunk = myChunks.Dequeue(); firstChunk.Upload(); @@ -156,22 +173,28 @@ public void Upload() private void OnCompleteChunk(VideoChunk chunk, string msg) { - Debug.Log(myChunks.Count); + //Destroy the chunk + Destroy(chunk); + //Make sure the queue is not empty - if (myChunks.Count != 0) { + if (myChunks.Count != 0) + { VideoChunk nextChunk = myChunks.Dequeue(); + OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); nextChunk.Upload(); + } else { + Debug.Log("Finished"); } } private void OnChunkError(VideoChunk chunk, string err) { - + Debug.LogError(err); } private void OnError(string err) { - + Debug.LogError(err); } } } \ No newline at end of file From 6c4ad8c4fe14d1149548c2e31850e90062ee696e Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 11:08:00 -0400 Subject: [PATCH 08/68] Adding events, proper styling and splitting VideoChunk from VimeoUploader --- .../Vimeo/Scripts/Services/VimepUploader.cs | 220 ++++++++---------- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 77 ++++++ Assets/Vimeo/Scripts/Utils/VideoChunk.cs.meta | 11 + 3 files changed, 181 insertions(+), 127 deletions(-) create mode 100644 Assets/Vimeo/Scripts/Utils/VideoChunk.cs create mode 100644 Assets/Vimeo/Scripts/Utils/VideoChunk.cs.meta diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index b7203b03..fd86b698 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -1,164 +1,63 @@ using System.IO; -using System; using System.Collections; using System.Collections.Generic; -using System.Text; using UnityEngine; using UnityEngine.Networking; using SimpleJSON; -/* - TODO: - - Format the whole code - - Get rid of unused namespaces - - Split functionality into seprate methods - - Split VideoChunk and VimeoUploader to seprate files -*/ - namespace Vimeo { - class VideoChunk : MonoBehaviour + class VimeoUploader : MonoBehaviour { - private int indexByte; - private string url; - private byte[] bytes; - private string file_path; - private int chuckSize; + //Events + public delegate void UploadAction(string status, float progress = 0.0f); + public event UploadAction OnUploadProgress; + public event UploadAction OnUploadError; + public event UploadAction OnUploadComplete; public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; - public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize) - { - bytes = new byte[_chucnkSize]; - file_path = _file_path; - indexByte = _indexByte; - url = _url; - } - - private void ReadBytes() - { - using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) - { - reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); - reader.Read(bytes, 0, bytes.Length); - } - } - - private void DisposeBytes() - { - Array.Clear(bytes, 0, bytes.Length); - } - - private IEnumerator SendTusRequest() - { - ReadBytes(); - using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) - { - uploadRequest.chunkedTransfer = false; - uploadRequest.method = "PATCH"; - uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); - uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); - - yield return VimeoApi.SendRequest(uploadRequest); - - if (uploadRequest.isNetworkError || uploadRequest.isHttpError) - { - string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; - OnChunckUploadError(this, concatErr); - } - else - { - OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); - } - } - DisposeBytes(); - } + //Private members + private Queue myChunks; - public void Upload() - { - StartCoroutine(SendTusRequest()); - } - } - class VimeoUploader : MonoBehaviour - { - public delegate void UploadAction(string status, float progress = 0.0f); - public event UploadAction OnUploadProgress; - private Queue myChunks; - private int numChunks; + //Public members public int maxChunkSize; + public int numChunks; + public IEnumerator Init(string _file, string _token, int _maxChunkSize = 1000) { myChunks = new Queue(); - maxChunkSize = _maxChunkSize; - FileInfo fileInfo = new FileInfo(_file); - Debug.Log("File size in bytes" + fileInfo.Length.ToString()); - string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileInfo.Length.ToString() + "\" } }"; using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { - //Prep headers - request.chunkedTransfer = false; - request.method = "POST"; - request.SetRequestHeader("Authorization", "bearer " + _token); - request.SetRequestHeader("Content-Type", "application/json"); - request.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); + UnityWebRequest videoResource = PrepareTusResourceRequest(request, _token); - yield return VimeoApi.SendRequest(request); + yield return VimeoApi.SendRequest(videoResource); - Debug.Log("After request"); - if (request.isNetworkError || request.isHttpError) + if (videoResource.isNetworkError || videoResource.isHttpError) { - OnError("[Error] " + request.error + " error code is: " + request.responseCode); + if (OnUploadError != null) + { + OnUploadError(videoResource.error + " error code is: " + videoResource.responseCode); + } } else { - JSONNode rawJSON = JSON.Parse(request.downloadHandler.text); - string tusUploadLink = rawJSON["upload"]["upload_link"].Value; - Debug.Log("[Vimeo] Secure tus upload link is: " + tusUploadLink); - - //Create the chunks - numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); - Debug.Log("Number of chunks is " + numChunks + " and file size is " + fileInfo.Length.ToString()); - for (int i = 0; i < numChunks; i++) - { - int indexByte = maxChunkSize * i; - VideoChunk chunk = this.gameObject.AddComponent(); - - //If we are at the last chunk set the max chunk size to the fractional remainder - if (i + 1 == numChunks) - { - int remainder = (int)fileInfo.Length - (maxChunkSize * i); - Debug.Log("Created last chunk and the remainder is: " + remainder); - chunk.Init(indexByte, tusUploadLink, _file, remainder); - } - else - { - chunk.Init(indexByte, tusUploadLink, _file, maxChunkSize); - } - - //Register evenets - chunk.OnChunckUploadComplete += OnCompleteChunk; - chunk.OnChunckUploadError += OnChunkError; - - //Push it to the queue - myChunks.Enqueue(chunk); - - } + string tusUploadLink = GetTusUploadLink(videoResource); + CreateChunks(_file, fileInfo, tusUploadLink); } } } - public void SetChunkSize(int size) { maxChunkSize = size; @@ -167,12 +66,22 @@ public void SetChunkSize(int size) public void Upload() { //Kick off the first chunk, currently will call other chunks via the OnCompleteChunk event + if (OnUploadProgress != null) + { + OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); + } VideoChunk firstChunk = myChunks.Dequeue(); firstChunk.Upload(); } private void OnCompleteChunk(VideoChunk chunk, string msg) { + //Emit the event + if (OnChunckUploadComplete != null) + { + OnChunckUploadComplete(chunk, msg); + } + //Destroy the chunk Destroy(chunk); @@ -180,21 +89,78 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) if (myChunks.Count != 0) { VideoChunk nextChunk = myChunks.Dequeue(); - OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); + // OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); nextChunk.Upload(); - } else { - Debug.Log("Finished"); + } + else + { + //Set the progress back to 0 + if (OnUploadProgress != null) + { + OnUploadProgress("Idle", 0.0f); + } + //Emit upload complete + if (OnUploadComplete != null) + { + OnUploadComplete("Completed upload!"); + } } } private void OnChunkError(VideoChunk chunk, string err) { - Debug.LogError(err); + if (OnChunckUploadError != null) + { + OnChunckUploadError(chunk, err); + } } + private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) + { + //Create the chunks + numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); - private void OnError(string err) + for (int i = 0; i < numChunks; i++) + { + int indexByte = maxChunkSize * i; + VideoChunk chunk = this.gameObject.AddComponent(); + chunk.hideFlags = HideFlags.HideInInspector; + + //If we are at the last chunk set the max chunk size to the fractional remainder + if (i + 1 == numChunks) + { + int remainder = (int)fileInfo.Length - (maxChunkSize * i); + Debug.Log("Created last chunk and the remainder is: " + remainder); + chunk.Init(indexByte, tusUploadLink, filePath, remainder); + } + else + { + chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); + } + + //Register evenets + chunk.OnChunckUploadComplete += OnCompleteChunk; + chunk.OnChunckUploadError += OnChunkError; + + //Push it to the queue + myChunks.Enqueue(chunk); + + } + } + private UnityWebRequest PrepareTusResourceRequest(UnityWebRequest req, string token) + { + //Prep headers + req.chunkedTransfer = false; + req.method = "POST"; + req.SetRequestHeader("Authorization", "bearer " + token); + req.SetRequestHeader("Content-Type", "application/json"); + req.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); + + return req; + } + private string GetTusUploadLink(UnityWebRequest response) { - Debug.LogError(err); + JSONNode rawJSON = JSON.Parse(response.downloadHandler.text); + return rawJSON["upload"]["upload_link"].Value; } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs new file mode 100644 index 00000000..f6792f7c --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -0,0 +1,77 @@ +using System.IO; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; + +namespace Vimeo +{ + class VideoChunk : MonoBehaviour + { + private int indexByte; + private string url; + private byte[] bytes; + private string file_path; + private int chuckSize; + + public delegate void UploadEvent(VideoChunk chunk, string msg = ""); + public event UploadEvent OnChunckUploadComplete; + public event UploadEvent OnChunckUploadError; + + public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize) + { + bytes = new byte[_chucnkSize]; + file_path = _file_path; + indexByte = _indexByte; + url = _url; + } + + private void ReadBytes() + { + using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) + { + reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); + reader.Read(bytes, 0, bytes.Length); + } + } + + private void DisposeBytes() + { + Array.Clear(bytes, 0, bytes.Length); + } + + private IEnumerator SendTusRequest() + { + ReadBytes(); + using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) + { + uploadRequest.chunkedTransfer = false; + uploadRequest.method = "PATCH"; + uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); + uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); + uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + + yield return VimeoApi.SendRequest(uploadRequest); + + if (uploadRequest.isNetworkError || uploadRequest.isHttpError) + { + string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; + OnChunckUploadError(this, concatErr); + } + else + { + OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); + } + } + DisposeBytes(); + } + + public void Upload() + { + StartCoroutine(SendTusRequest()); + } + + } +} \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs.meta b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs.meta new file mode 100644 index 00000000..1d23e69a --- /dev/null +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f76db71a8b2f8429591b19563561caa2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From d6b52c69585c76f4f5dee3e2273bde44d4f0c6aa Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 11:21:40 -0400 Subject: [PATCH 09/68] =?UTF-8?q?Hiding=20all=20components=20additional=20?= =?UTF-8?q?components=20in=20recorder=20scene=20from=20the=20inspector=20?= =?UTF-8?q?=F0=9F=99=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plus formatting the changed files --- .../Vimeo/Scripts/Recorder/EncoderManager.cs | 74 ++++++++------ .../Scripts/Recorder/Input/VideoInput.cs | 55 ++++++----- .../Scripts/Recorder/RecorderController.cs | 86 +++++++++++------ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 96 ++++++++++++------- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 1 + .../Vimeo/Scripts/Services/VimepUploader.cs | 5 +- 6 files changed, 199 insertions(+), 118 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs b/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs index 89933581..c674220e 100644 --- a/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs +++ b/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs @@ -1,5 +1,5 @@ #if UNITY_2017_3_OR_NEWER && UNITY_EDITOR - #define MEDIA_ENCODER_SUPPORT +#define MEDIA_ENCODER_SUPPORT #endif using UnityEngine; @@ -11,26 +11,32 @@ using RenderHeads.Media.AVProMovieCapture; #endif -namespace Vimeo.Recorder +namespace Vimeo.Recorder { public class EncoderManager : MonoBehaviour { private VimeoRecorder _recorder; public bool isRecording = false; - #if VIMEO_AVPRO_CAPTURE_SUPPORT +#if VIMEO_AVPRO_CAPTURE_SUPPORT private CaptureBase _avproEncoder; - #endif +#endif - #if MEDIA_ENCODER_SUPPORT - private RecorderController _vimeoEncoder; - #endif +#if MEDIA_ENCODER_SUPPORT + private RecorderController _vimeoEncoder; +#endif + + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } public void Init(VimeoRecorder r) { _recorder = r; - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder = gameObject.AddComponent(); _vimeoEncoder.Init(_recorder); @@ -38,7 +44,8 @@ public void Init(VimeoRecorder r) Debug.LogError("[Vimeo] Recording is only avaialabe in 2017.2 or higher."); #endif } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { + else if (_recorder.encoderType == EncoderType.AVProMovieCapture) + { #if VIMEO_AVPRO_CAPTURE_SUPPORT _avproEncoder = r.avproEncoder; #endif @@ -49,12 +56,14 @@ public void BeginRecording() { isRecording = true; - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder.BeginRecording(); #endif } - else { + else + { #if VIMEO_AVPRO_CAPTURE_SUPPORT _avproEncoder.StartCapture(); #endif @@ -63,14 +72,16 @@ public void BeginRecording() public void EndRecording() { - isRecording = false; + isRecording = false; - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder.EndRecording(); #endif } - else { + else + { #if VIMEO_AVPRO_CAPTURE_SUPPORT // _avproEncoder.StartCapture(); #endif @@ -86,10 +97,12 @@ public void CancelRecording() public void AddFrame() { #if MEDIA_ENCODER_SUPPORT - if (_recorder.encoderType == EncoderType.MediaEncoder) { - _vimeoEncoder.AddFrame(); + if (_recorder.encoderType == EncoderType.MediaEncoder) + { + _vimeoEncoder.AddFrame(); } - else { + else + { Debug.LogWarning("[VimeoRecorder] AddFrame is only available for MediaEncoder."); } #endif @@ -97,28 +110,32 @@ public void AddFrame() public string GetVideoFilePath() { - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { #if MEDIA_ENCODER_SUPPORT return _vimeoEncoder.encodedFilePath; #endif } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { + else if (_recorder.encoderType == EncoderType.AVProMovieCapture) + { #if VIMEO_AVPRO_CAPTURE_SUPPORT return _avproEncoder.LastFilePath; #endif } - + return null; } public int GetCurrentFrame() { - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { #if MEDIA_ENCODER_SUPPORT return _vimeoEncoder.currentFrame; #endif } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { + else if (_recorder.encoderType == EncoderType.AVProMovieCapture) + { #if VIMEO_AVPRO_CAPTURE_SUPPORT Debug.LogWarning("[VimeoRecorder] GetCurrentFrame not supported for AVProMovieCapture"); return -1; @@ -156,10 +173,12 @@ public void DeleteVideoFile() public void ManualFrameCapture() { #if MEDIA_ENCODER_SUPPORT - if (_recorder.encoderType == EncoderType.MediaEncoder) { + if (_recorder.encoderType == EncoderType.MediaEncoder) + { _vimeoEncoder.manualFrameCapture = true; } - else { + else + { Debug.LogWarning("[VimeoRecorder] ManualFrameCapture is only available for MediaEncoder."); } #endif @@ -168,12 +187,13 @@ public void ManualFrameCapture() void OnDestroy() { #if MEDIA_ENCODER_SUPPORT - if (_vimeoEncoder != null) { + if (_vimeoEncoder != null) + { Destroy(_vimeoEncoder); } #endif } - + void Update() { #if VIMEO_AVPRO_CAPTURE_SUPPORT @@ -196,6 +216,6 @@ void Update() } #endif } - + } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Recorder/Input/VideoInput.cs b/Assets/Vimeo/Scripts/Recorder/Input/VideoInput.cs index 704e1d98..0efaa801 100644 --- a/Assets/Vimeo/Scripts/Recorder/Input/VideoInput.cs +++ b/Assets/Vimeo/Scripts/Recorder/Input/VideoInput.cs @@ -11,18 +11,21 @@ public class VideoInput : MonoBehaviour [HideInInspector] public RecorderController encoder; bool m_ModifiedResolution; - + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } public int outputWidth { get; protected set; } public int outputHeight { get; protected set; } - + public virtual Texture GetFrame() { return new Texture2D(1, 1); } public virtual void StartFrame() { } public virtual void EndFrame() { } - public virtual void BeginRecording() - { + public virtual void BeginRecording() + { Screen.orientation = ScreenOrientation.Landscape; - + int w, h; GameViewSize.GetGameRenderSize(out w, out h); @@ -30,34 +33,37 @@ public virtual void BeginRecording() switch (recorder.defaultResolution) { case Resolution.Window: - { - outputWidth = (w + 1) & ~1; - outputHeight = (h + 1) & ~1; - break; - } + { + outputWidth = (w + 1) & ~1; + outputHeight = (h + 1) & ~1; + break; + } default: - { - outputHeight = (int)recorder.defaultResolution; - outputWidth = (int)(outputHeight * AspectRatioHelper.GetRealAR(recorder.defaultAspectRatio)); + { + outputHeight = (int)recorder.defaultResolution; + outputWidth = (int)(outputHeight * AspectRatioHelper.GetRealAR(recorder.defaultAspectRatio)); - outputWidth = (outputWidth + 1) & ~1; - outputHeight = (outputHeight + 1) & ~1; - break; - } + outputWidth = (outputWidth + 1) & ~1; + outputHeight = (outputHeight + 1) & ~1; + break; + } } - + //Debug.Log("Screen resolution: " + w + "x" + h); if (w != outputWidth || h != outputHeight) { Debug.Log("[VimeoRecorder] Setting window size to: " + outputWidth + "x" + outputHeight); var size = GameViewSize.SetCustomSize(outputWidth, outputHeight) ?? GameViewSize.AddSize(outputWidth, outputHeight); - if (GameViewSize.m_ModifiedResolutionCount == 0) { + if (GameViewSize.m_ModifiedResolutionCount == 0) + { GameViewSize.BackupCurrentSize(); } - else { - if (size != GameViewSize.currentSize) { + else + { + if (size != GameViewSize.currentSize) + { Debug.LogError("[VimeoRecorder] Requestion a resultion change while a recorder's input has already requested one! Undefined behaviour."); } } @@ -69,13 +75,14 @@ public virtual void BeginRecording() #endif } - public virtual void EndRecording() - { + public virtual void EndRecording() + { #if UNITY_EDITOR if (m_ModifiedResolution) { GameViewSize.m_ModifiedResolutionCount--; - if (GameViewSize.m_ModifiedResolutionCount == 0) { + if (GameViewSize.m_ModifiedResolutionCount == 0) + { GameViewSize.RestoreSize(); } } diff --git a/Assets/Vimeo/Scripts/Recorder/RecorderController.cs b/Assets/Vimeo/Scripts/Recorder/RecorderController.cs index ff9abed0..c6290715 100644 --- a/Assets/Vimeo/Scripts/Recorder/RecorderController.cs +++ b/Assets/Vimeo/Scripts/Recorder/RecorderController.cs @@ -8,7 +8,7 @@ using System.Collections; using System.Collections.Generic; -namespace Vimeo.Recorder +namespace Vimeo.Recorder { public class RecorderController : MonoBehaviour { @@ -36,6 +36,10 @@ public class RecorderController : MonoBehaviour private AudioInput audioInput; #endif + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } public void Init(VimeoRecorder r) { recorder = r; @@ -61,10 +65,12 @@ private void BeginMediaEncoderRecording() { InitInputs(); - if (recorder.realTime) { + if (recorder.realTime) + { Application.targetFrameRate = recorder.frameRate; } - else { + else + { Time.captureFramerate = recorder.frameRate; } @@ -87,7 +93,7 @@ private void BeginMediaEncoderRecording() videoAttrs = new VideoTrackAttributes { frameRate = new MediaRational(recorder.frameRate), - width = (uint)videoInput.outputWidth, + width = (uint)videoInput.outputWidth, height = (uint)videoInput.outputHeight, includeAlpha = false }; @@ -95,11 +101,13 @@ private void BeginMediaEncoderRecording() encodedFilePath = Path.Combine(outputPath, GetFileName()); Debug.Log("[VimeoRecorder] Recording to " + GetFileName()); - if (!recorder.realTime) { + if (!recorder.realTime) + { recorder.recordAudio = false; - } + } - if (recorder.recordAudio) { + if (recorder.recordAudio) + { #if UNITY_2018_1_OR_NEWER audioInput.BeginRecording(); encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs, audioAttrs); @@ -107,7 +115,8 @@ private void BeginMediaEncoderRecording() encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs); #endif } - else { + else + { encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs); } } @@ -121,23 +130,26 @@ public string GetFileName() public void EndRecording() { - if (encoder != null) { + if (encoder != null) + { encoder.Dispose(); encoder = null; } - if (videoInput != null) { + if (videoInput != null) + { videoInput.EndRecording(); - Release(videoInput); + Release(videoInput); } #if UNITY_2018_1_OR_NEWER - if (audioInput != null) { + if (audioInput != null) + { if (recorder.recordAudio) audioInput.EndRecording(); Release(audioInput); } #endif - + Time.captureFramerate = 0; currentFrame = 0; @@ -151,19 +163,22 @@ public void DeleteVideoFile() IEnumerator RecordFrame() { yield return new WaitForEndOfFrame(); - if (!manualFrameCapture) { + if (!manualFrameCapture) + { AddFrame(); } } public void AddFrame() { - if (encoder != null && isRecording) { + if (encoder != null && isRecording) + { encoder.AddFrame(videoInput.GetFrame() as Texture2D); videoInput.EndFrame(); #if UNITY_2018_1_OR_NEWER - if (recorder.recordAudio) { + if (recorder.recordAudio) + { audioInput.StartFrame(); encoder.AddSamples(audioInput.GetBuffer()); audioInput.EndFrame(); @@ -176,29 +191,36 @@ public void AddFrame() public void LateUpdate() { - if (encoder != null && isRecording) { - if (recorder.recordMode == RecordMode.Duration) { - if (currentFrame > recorder.frameRate * recorder.recordDuration) { + if (encoder != null && isRecording) + { + if (recorder.recordMode == RecordMode.Duration) + { + if (currentFrame > recorder.frameRate * recorder.recordDuration) + { recorder.EndRecording(); } - else { + else + { StartCoroutine(RecordFrame()); } } - else { + else + { StartCoroutine(RecordFrame()); } } } - + private void InitInputs() { - if (videoInput != null) { + if (videoInput != null) + { Release(videoInput); } #if UNITY_2018_1_OR_NEWER - if (audioInput != null) { + if (audioInput != null) + { Release(audioInput); } @@ -207,7 +229,8 @@ private void InitInputs() audioInput.recorder = recorder; #endif - switch(recorder.defaultVideoInput) { + switch (recorder.defaultVideoInput) + { case VideoInputType.Screen: videoInput = gameObject.AddComponent(); break; @@ -218,10 +241,10 @@ private void InitInputs() videoInput = gameObject.AddComponent(); break; case VideoInputType.RenderTexture: - videoInput = gameObject.AddComponent(); - break; + videoInput = gameObject.AddComponent(); + break; } - + videoInput.recorder = recorder; } @@ -232,9 +255,12 @@ void OnDestroy() public void Release(MonoBehaviour obj) { - if (Application.isEditor) { + if (Application.isEditor) + { DestroyImmediate(obj); - } else { + } + else + { Destroy(obj); } } diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 428d5a83..a6e8c441 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -7,7 +7,7 @@ namespace Vimeo.Recorder { - public class VimeoPublisher : MonoBehaviour + public class VimeoPublisher : MonoBehaviour { public delegate void UploadAction(string status, float progress); public event UploadAction OnUploadProgress; @@ -21,18 +21,22 @@ public class VimeoPublisher : MonoBehaviour private VimeoVideo video; private Coroutine saveCoroutine; - - public void Init(VimeoRecorder _recorder) + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } + public void Init(VimeoRecorder _recorder) { recorder = _recorder; - - if (vimeoApi == null) { + + if (vimeoApi == null) + { vimeoApi = gameObject.AddComponent(); - vimeoApi.OnPatchComplete += VideoUpdated; + vimeoApi.OnPatchComplete += VideoUpdated; vimeoApi.OnUploadComplete += UploadComplete; vimeoApi.OnUploadProgress += UploadProgress; - vimeoApi.OnError += ApiError; - vimeoApi.OnNetworkError += NetworkError; + vimeoApi.OnError += ApiError; + vimeoApi.OnNetworkError += NetworkError; vimeoApi.token = recorder.GetVimeoToken(); } @@ -40,28 +44,32 @@ public void Init(VimeoRecorder _recorder) public string GetVimeoPermalink() { - if (recorder.videoPermalink != null) { - if (recorder.defaultShareLink == LinkType.ReviewPage) { + if (recorder.videoPermalink != null) + { + if (recorder.defaultShareLink == LinkType.ReviewPage) + { return recorder.videoReviewPermalink; - } - else { + } + else + { return recorder.videoPermalink; } - } - + } + return "https://vimeo.com/" + video.id; } public void PublishVideo(string filename) { - Debug.Log("[VimeoRecorder] Uploading to Vimeo"); + Debug.Log("[VimeoRecorder] Uploading to Vimeo"); vimeoApi.UploadVideoFile(filename); } private void UploadProgress(string status, float progress) { - if (OnUploadProgress != null) { + if (OnUploadProgress != null) + { OnUploadProgress(status, progress); } } @@ -73,20 +81,23 @@ private void UploadComplete(string video_uri) video = new VimeoVideo("", video_uri); #if UNITY_2018_1_OR_NEWER - if (recorder.defaultVideoInput == VideoInputType.Camera360) { + if (recorder.defaultVideoInput == VideoInputType.Camera360) + { vimeoApi.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); } #endif vimeoApi.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); - if (recorder.enableDownloads == false) { + if (recorder.enableDownloads == false) + { vimeoApi.SetVideoDownload(recorder.enableDownloads); } vimeoApi.SetVideoComments(recorder.commentMode); vimeoApi.SetVideoReviewPage(recorder.enableReviewPage); SetVideoName(recorder.GetVideoName()); - if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { + if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) + { vimeoApi.SetVideoPassword(recorder.videoPassword); } SetVideoPrivacyMode(recorder.privacyMode); @@ -98,11 +109,13 @@ private void VideoUpdated(string response) recorder.videoPermalink = json["link"]; recorder.videoReviewPermalink = json["review_link"]; - if (recorder.openInBrowser == true) { + if (recorder.openInBrowser == true) + { OpenVideo(); } - if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { + if (recorder.currentFolder != null && recorder.currentFolder.uri != null) + { vimeoApi.AddVideoToFolder(video, recorder.currentFolder); } @@ -111,7 +124,8 @@ private void VideoUpdated(string response) private void NetworkError(string error_message) { - if (OnNetworkError != null) { + if (OnNetworkError != null) + { OnNetworkError("It seems like you are not connected to the internet or are having connection problems."); } } @@ -120,35 +134,44 @@ private void ApiError(string response) { JSONNode json = JSON.Parse(response); - if (json["invalid_parameters"] != null) { + if (json["invalid_parameters"] != null) + { - for (int i = 0; i < json["invalid_parameters"].Count; i++) { + for (int i = 0; i < json["invalid_parameters"].Count; i++) + { // TODO use .Value - if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.download\"") { - if (OnNetworkError != null) { + if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.download\"") + { + if (OnNetworkError != null) + { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } } - else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") { - if (OnNetworkError != null) { + else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") + { + if (OnNetworkError != null) + { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } } - else { - if (OnNetworkError != null) { + else + { + if (OnNetworkError != null) + { OnNetworkError(json["invalid_parameters"][i]["field"] + ": " + json["invalid_parameters"][i]["error"]); } } } - + } UploadProgress("SaveInfoComplete", 1f); } public void SetVideoName(string title) { - if (title != null && title != "") { - if (saveCoroutine != null) { StopCoroutine (saveCoroutine); } // DRY + if (title != null && title != "") + { + if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } // DRY vimeoApi.SetVideoName(title); saveCoroutine = StartCoroutine("SaveVideo"); } @@ -156,7 +179,7 @@ public void SetVideoName(string title) public void SetVideoPrivacyMode(VimeoApi.PrivacyModeDisplay mode) { - if (saveCoroutine != null) { StopCoroutine (saveCoroutine); } + if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } vimeoApi.SetVideoViewPrivacy(mode); saveCoroutine = StartCoroutine("SaveVideo"); } @@ -165,7 +188,8 @@ private IEnumerator SaveVideo() { yield return new WaitForSeconds(1f); - if (video != null) { + if (video != null) + { vimeoApi.SaveVideo(video); } } @@ -182,7 +206,7 @@ public void OpenSettings() void OnDestroy() { - Dispose(); + Dispose(); } public void Dispose() diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 60c134cd..b7d70ed3 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -58,6 +58,7 @@ public enum CommentMode void Start() { + this.hideFlags = HideFlags.HideInInspector; form = new WWWForm(); } diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimepUploader.cs index fd86b698..37ffa8ea 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimepUploader.cs @@ -26,7 +26,10 @@ class VimeoUploader : MonoBehaviour //Public members public int maxChunkSize; public int numChunks; - + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } public IEnumerator Init(string _file, string _token, int _maxChunkSize = 1000) { myChunks = new Queue(); From 0246e39d0baac3ca79ef59c489d16a4d86a86e82 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 11:28:52 -0400 Subject: [PATCH 10/68] Hiding video controller from the inspector as well --- Assets/Vimeo/Scripts/Player/VideoController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Assets/Vimeo/Scripts/Player/VideoController.cs b/Assets/Vimeo/Scripts/Player/VideoController.cs index 5088442c..2f61e6d1 100644 --- a/Assets/Vimeo/Scripts/Player/VideoController.cs +++ b/Assets/Vimeo/Scripts/Player/VideoController.cs @@ -35,7 +35,10 @@ public class VideoController : MonoBehaviour { public long seekFrame = 0; private long prevFrameIndex = 0; private bool frameStepping = false; - + private void Start() + { + this.hideFlags = HideFlags.HideInInspector; + } public void Setup() { if (videoScreenObject != null) { From c242d0e15ffbcac0b7122f36e6a3eee81216fec3 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 11:46:01 -0400 Subject: [PATCH 11/68] Fixing typo in file name `VimepUploader.cs` should be `VimeoUploader.cs` --- .../Scripts/Services/{VimepUploader.cs => VimeoUploader.cs} | 0 .../Services/{VimepUploader.cs.meta => VimeoUploader.cs.meta} | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename Assets/Vimeo/Scripts/Services/{VimepUploader.cs => VimeoUploader.cs} (100%) rename Assets/Vimeo/Scripts/Services/{VimepUploader.cs.meta => VimeoUploader.cs.meta} (83%) diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs similarity index 100% rename from Assets/Vimeo/Scripts/Services/VimepUploader.cs rename to Assets/Vimeo/Scripts/Services/VimeoUploader.cs diff --git a/Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs.meta similarity index 83% rename from Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta rename to Assets/Vimeo/Scripts/Services/VimeoUploader.cs.meta index 676edc69..380f8357 100644 --- a/Assets/Vimeo/Scripts/Services/VimepUploader.cs.meta +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 28d9d304dbb6a49488055b6ccb0febfd +guid: f36deada9e3044089a2ae8fc8eef3209 MonoImporter: externalObjects: {} serializedVersion: 2 From 77a0b234f5039b355593fe7394ea00dfc1975293 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 18:03:57 -0400 Subject: [PATCH 12/68] Implementing VimeoUploader into the VimeoPublisher class --- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 48 ++-- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 252 +++++++++++------- .../Vimeo/Scripts/Services/VimeoUploader.cs | 93 ++++--- 3 files changed, 236 insertions(+), 157 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index a6e8c441..d62baec0 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -17,7 +17,7 @@ public class VimeoPublisher : MonoBehaviour [HideInInspector] public VimeoRecorder recorder; // recorder contains all the settings - private VimeoApi vimeoApi; + private VimeoUploader vimeoUploader; private VimeoVideo video; private Coroutine saveCoroutine; @@ -29,16 +29,14 @@ public void Init(VimeoRecorder _recorder) { recorder = _recorder; - if (vimeoApi == null) + if (vimeoUploader == null) { - vimeoApi = gameObject.AddComponent(); - vimeoApi.OnPatchComplete += VideoUpdated; - vimeoApi.OnUploadComplete += UploadComplete; - vimeoApi.OnUploadProgress += UploadProgress; - vimeoApi.OnError += ApiError; - vimeoApi.OnNetworkError += NetworkError; - - vimeoApi.token = recorder.GetVimeoToken(); + vimeoUploader = gameObject.AddComponent(); + vimeoUploader.Init(recorder.GetVimeoToken()); + + vimeoUploader.vimeoApi.OnPatchComplete += VideoUpdated; + vimeoUploader.OnUploadProgress += UploadProgress; + vimeoUploader.OnUploadComplete += UploadComplete; } } @@ -62,11 +60,9 @@ public string GetVimeoPermalink() public void PublishVideo(string filename) { Debug.Log("[VimeoRecorder] Uploading to Vimeo"); - vimeoApi.UploadVideoFile(filename); + vimeoUploader.Upload(filename); } - - - private void UploadProgress(string status, float progress) + void UploadProgress(string status, float progress) { if (OnUploadProgress != null) { @@ -74,7 +70,7 @@ private void UploadProgress(string status, float progress) } } - private void UploadComplete(string video_uri) + void UploadComplete(string video_uri, float number) { UploadProgress("SavingInfo", .999f); @@ -83,22 +79,22 @@ private void UploadComplete(string video_uri) #if UNITY_2018_1_OR_NEWER if (recorder.defaultVideoInput == VideoInputType.Camera360) { - vimeoApi.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); + vimeoUploader.vimeoApi.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); } #endif - vimeoApi.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); + vimeoUploader.vimeoApi.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); if (recorder.enableDownloads == false) { - vimeoApi.SetVideoDownload(recorder.enableDownloads); + vimeoUploader.vimeoApi.SetVideoDownload(recorder.enableDownloads); } - vimeoApi.SetVideoComments(recorder.commentMode); - vimeoApi.SetVideoReviewPage(recorder.enableReviewPage); + vimeoUploader.vimeoApi.SetVideoComments(recorder.commentMode); + vimeoUploader.vimeoApi.SetVideoReviewPage(recorder.enableReviewPage); SetVideoName(recorder.GetVideoName()); if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { - vimeoApi.SetVideoPassword(recorder.videoPassword); + vimeoUploader.vimeoApi.SetVideoPassword(recorder.videoPassword); } SetVideoPrivacyMode(recorder.privacyMode); } @@ -116,7 +112,7 @@ private void VideoUpdated(string response) if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { - vimeoApi.AddVideoToFolder(video, recorder.currentFolder); + vimeoUploader.vimeoApi.AddVideoToFolder(video, recorder.currentFolder); } UploadProgress("SaveInfoComplete", 1f); @@ -172,7 +168,7 @@ public void SetVideoName(string title) if (title != null && title != "") { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } // DRY - vimeoApi.SetVideoName(title); + vimeoUploader.vimeoApi.SetVideoName(title); saveCoroutine = StartCoroutine("SaveVideo"); } } @@ -180,7 +176,7 @@ public void SetVideoName(string title) public void SetVideoPrivacyMode(VimeoApi.PrivacyModeDisplay mode) { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } - vimeoApi.SetVideoViewPrivacy(mode); + vimeoUploader.vimeoApi.SetVideoViewPrivacy(mode); saveCoroutine = StartCoroutine("SaveVideo"); } @@ -190,7 +186,7 @@ private IEnumerator SaveVideo() if (video != null) { - vimeoApi.SaveVideo(video); + vimeoUploader.vimeoApi.SaveVideo(video); } } @@ -211,7 +207,7 @@ void OnDestroy() public void Dispose() { - Destroy(vimeoApi); + Destroy(vimeoUploader); } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index b7d70ed3..f1e0db05 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -9,9 +9,9 @@ namespace Vimeo { - [ExecuteInEditMode] + [ExecuteInEditMode] public class VimeoApi : MonoBehaviour - { + { public enum PrivacyModeDisplay { Anyone, @@ -69,30 +69,32 @@ public void GetVideoFileUrlByVimeoId(int video_id, string fields = "name,uri,dur public void GetUserFolders() { - StartCoroutine("Request", "/me/folders?fields=name,uri"); + StartCoroutine("Request", "/me/folders?fields=name,uri"); } public void AddVideoToFolder(VimeoVideo video, VimeoFolder folder) { - if (folder.id > 0 && video.uri != null) { + if (folder.id > 0 && video.uri != null) + { IEnumerator coroutine = Put("/me/folders/" + folder.id + "/videos?uris=" + video.uri); - StartCoroutine(coroutine); + StartCoroutine(coroutine); } } public void GetRecentUserVideos(string fields = "name,uri") { - StartCoroutine("Request", "/me/videos?fields=" + fields + "&per_page=100"); + StartCoroutine("Request", "/me/videos?fields=" + fields + "&per_page=100"); } public void GetVideosInFolder(VimeoFolder folder, string fields = "name,uri") { - StartCoroutine("Request", "/me/folders/" + folder.id + "/videos?fields=" + fields + "&per_page=100"); + StartCoroutine("Request", "/me/folders/" + folder.id + "/videos?fields=" + fields + "&per_page=100"); } - public void SetVideoViewPrivacy(PrivacyModeDisplay mode) + public void SetVideoViewPrivacy(PrivacyModeDisplay mode) { - switch (mode) { + switch (mode) + { case PrivacyModeDisplay.Anyone: form.AddField("privacy.view", VimeoApi.PrivacyMode.anybody.ToString()); @@ -109,16 +111,17 @@ public void SetVideoViewPrivacy(PrivacyModeDisplay mode) case PrivacyModeDisplay.HideThisFromVimeo: form.AddField("privacy.view", VimeoApi.PrivacyMode.disable.ToString()); break; - + case PrivacyModeDisplay.OnlyPeopleWithAPassword: form.AddField("privacy.view", VimeoApi.PrivacyMode.password.ToString()); break; } } - public void SetVideoComments(CommentMode mode) + public void SetVideoComments(CommentMode mode) { - switch (mode) { + switch (mode) + { case CommentMode.Anyone: form.AddField("privacy.comments", "anybody"); break; @@ -133,22 +136,22 @@ public void SetVideoComments(CommentMode mode) } } - public void SetVideoDownload(bool enabled) + public void SetVideoDownload(bool enabled) { form.AddField("privacy.download", enabled ? "true" : "false"); } - public void SetVideoReviewPage(bool enabled) + public void SetVideoReviewPage(bool enabled) { form.AddField("review_page.active", enabled ? "true" : "false"); } - public void SetVideoPassword(string password) + public void SetVideoPassword(string password) { form.AddField("password", password); } - public void SetVideoName(string name) + public void SetVideoName(string name) { form.AddField("name", name); } @@ -172,34 +175,41 @@ public void SaveVideo(VimeoVideo video) public void UploadVideoFile(string file_path) { video_file_path = file_path; - StartCoroutine(GetTicket()); - } + StartCoroutine(GetTicket()); + } IEnumerator GetTicket() { - if (OnUploadProgress != null) { + if (OnUploadProgress != null) + { OnUploadProgress("Authorizing", 0); } WWWForm form = new WWWForm(); form.AddField("type", "streaming"); - using (UnityWebRequest request = UnityWebRequest.Post(API_URL + "/me/videos", form)) { - PrepareHeaders(request , "3.2"); + using (UnityWebRequest request = UnityWebRequest.Post(API_URL + "/me/videos", form)) + { + PrepareHeaders(request, "3.2"); yield return VimeoApi.SendRequest(request); - if (IsNetworkError(request)) { - if (OnNetworkError != null) { + if (IsNetworkError(request)) + { + if (OnNetworkError != null) + { OnNetworkError(request.error); } - } - else { + } + else + { VimeoTicket ticket = VimeoTicket.CreateFromJSON(request.downloadHandler.text); - if (ticket.error == null) { + if (ticket.error == null) + { StartCoroutine(UploadVideo(ticket)); - } - else { + } + else + { Debug.LogError(ticket.error + " " + ticket.developer_message); } } @@ -208,94 +218,99 @@ IEnumerator GetTicket() IEnumerator UploadVideo(VimeoTicket ticket) { - if (OnUploadProgress != null) { + if (OnUploadProgress != null) + { OnUploadProgress("Uploading", 0); } - // byte[] data = new byte[0]; - // bool success = false; + byte[] data = new byte[0]; + bool success = false; // Using try/catch to wait for video to finish being - // while (success == false) { - // try { - // // Get local video file and store it in a byte array for uploading - // data = File.ReadAllBytes(video_file_path); - // success = true; - // } - // catch (IOException e) { - // // TODO: fix this ugly code! - // Debug.Log("File is being accessed by another process. " + e.Message); - // } - // } - - // FileInfo video_file = new FileInfo(video_file_path); - - VimeoUploader tus_uploader = this.gameObject.AddComponent(); - yield return tus_uploader.Init(video_file_path, token); - tus_uploader.Upload(); + while (success == false) { + try { + // Get local video file and store it in a byte array for uploading + data = File.ReadAllBytes(video_file_path); + success = true; + } + catch (IOException e) { + // TODO: fix this ugly code! + Debug.Log("File is being accessed by another process. " + e.Message); + } + } + + FileInfo video_file = new FileInfo(video_file_path); // Upload to the Vimeo server - // using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { - // uploader = request; - // request.chunkedTransfer = false; - // request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); - // yield return VimeoApi.SendRequest(request); + using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { + uploader = request; + request.chunkedTransfer = false; + request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); + yield return VimeoApi.SendRequest(request); - // uploader = null; + uploader = null; - // if (IsNetworkError(request)) { - // if (OnNetworkError != null) { - // OnNetworkError(request.error); - // } - // } - // else { - // StartCoroutine(VerifyUpload(ticket)); - // } - // } + if (IsNetworkError(request)) { + if (OnNetworkError != null) { + OnNetworkError(request.error); + } + } + else { + StartCoroutine(VerifyUpload(ticket)); + } + } } IEnumerator VerifyUpload(VimeoTicket ticket) { - if (OnUploadProgress != null) { + if (OnUploadProgress != null) + { OnUploadProgress("Verifying", 0.9999999f); } byte[] data = new byte[] { 0x00 }; - using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { + using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) + { request.chunkedTransfer = false; request.SetRequestHeader("Content-Range", "bytes */*"); yield return VimeoApi.SendRequest(request); - if (request.responseCode == 308) { + if (request.responseCode == 308) + { StartCoroutine(CompleteUpload(ticket)); - } - else { + } + else + { Debug.Log(request.responseCode); } } } - IEnumerator CompleteUpload(VimeoTicket ticket) + public IEnumerator CompleteUpload(VimeoTicket ticket) { - if (OnUploadProgress != null) { + if (OnUploadProgress != null) + { OnUploadProgress("Complete", 1f); } - using (UnityWebRequest request = UnityWebRequest.Delete(API_URL + ticket.complete_uri)) { + using (UnityWebRequest request = UnityWebRequest.Delete(API_URL + ticket.complete_uri)) + { PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (OnUploadComplete != null) { + if (OnUploadComplete != null) + { OnUploadComplete(request.GetResponseHeader("Location")); } } } - IEnumerator Patch(string url) + public IEnumerator Patch(string url) { - using (UnityWebRequest request = UnityWebRequest.Post(url, form)) { + using (UnityWebRequest request = UnityWebRequest.Post(url, form)) + { PrepareHeaders(request); request.SetRequestHeader("X-HTTP-Method-Override", "PATCH"); yield return VimeoApi.SendRequest(request); @@ -303,36 +318,72 @@ IEnumerator Patch(string url) // Reset the form form = new WWWForm(); - if (request.responseCode != 200) { + if (request.responseCode != 200) + { Debug.LogError(request.downloadHandler.text); if (OnError != null) OnError(request.downloadHandler.text); } - else if (OnPatchComplete != null) { + else if (OnPatchComplete != null) + { OnPatchComplete(request.downloadHandler.text); } } } + public IEnumerator RequestTusResource(string api_path, long fileByteCount) + { + string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileByteCount.ToString() + "\" } }"; + if (token != null) + { + using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) + { + PrepareTusHeaders(request); + yield return VimeoApi.SendRequest(request); + + if (request.error != null) + { + Debug.Log(request.error); + Debug.Log(request.responseCode); + Debug.LogError(request.downloadHandler.text); + if (OnError != null) OnError(request.downloadHandler.text); + } + else + { + if (OnRequestComplete != null) + { + OnRequestComplete(request.downloadHandler.text); + } + } + } + } + } IEnumerator Put(string api_path) { - if (token != null) { + if (token != null) + { byte[] data = new byte[] { 0x00 }; - using(UnityWebRequest request = UnityWebRequest.Put(API_URL + api_path, data)) { + using (UnityWebRequest request = UnityWebRequest.Put(API_URL + api_path, data)) + { PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (request.error != null) { + if (request.error != null) + { Debug.LogError(request.downloadHandler.text); if (OnError != null) OnError(request.downloadHandler.text); - } - else { - // TODO create event hook + } + else + { + if (OnRequestComplete != null) + { + OnRequestComplete(request.downloadHandler.text); + } } } } } - IEnumerator Request(string api_path) + public IEnumerator Request(string api_path) { if (token != null) { @@ -340,33 +391,46 @@ IEnumerator Request(string api_path) PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (request.responseCode != 200) { - if (request.responseCode == 401) { + if (request.responseCode != 200) + { + if (request.responseCode == 401) + { Debug.LogError("[VimeoApi] 401 Unauthorized request."); } - if (OnNetworkError != null && IsNetworkError(request)) { + if (OnNetworkError != null && IsNetworkError(request)) + { OnNetworkError(request.error); } - if (OnError != null && !IsNetworkError(request)) { + if (OnError != null && !IsNetworkError(request)) + { OnError(request.downloadHandler.text); } } - else if (OnRequestComplete != null) { + else if (OnRequestComplete != null) + { OnRequestComplete(request.downloadHandler.text); } } } - + private void PrepareTusHeaders(UnityWebRequest r, string apiVersion = "3.4") + { + r.chunkedTransfer = false; + r.method = "POST"; + r.SetRequestHeader("Authorization", "bearer " + token); + r.SetRequestHeader("Content-Type", "application/json"); + r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); + } private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") { r.chunkedTransfer = false; - r.SetRequestHeader("Authorization", "Bearer " + token); + r.SetRequestHeader("Authorization", "bearer " + token); r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); } - public static bool IsNetworkError(UnityWebRequest req) { + public static bool IsNetworkError(UnityWebRequest req) + { #if UNITY_2017_1_OR_NEWER return req.isNetworkError; #else @@ -374,7 +438,8 @@ public static bool IsNetworkError(UnityWebRequest req) { #endif } - public static AsyncOperation SendRequest(UnityWebRequest req) { + public static AsyncOperation SendRequest(UnityWebRequest req) + { #if UNITY_2017_2_OR_NEWER return req.SendWebRequest(); #else @@ -384,7 +449,8 @@ public static AsyncOperation SendRequest(UnityWebRequest req) { void FixedUpdate() { - if (OnUploadProgress != null && uploader != null && uploader.uploadProgress != 1) { + if (OnUploadProgress != null && uploader != null && uploader.uploadProgress != 1) + { OnUploadProgress("Uploading", uploader.uploadProgress); } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 37ffa8ea..be15d4e6 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -4,6 +4,7 @@ using UnityEngine; using UnityEngine.Networking; using SimpleJSON; +using Vimeo; namespace Vimeo { @@ -21,6 +22,11 @@ class VimeoUploader : MonoBehaviour //Private members private Queue myChunks; + public VimeoApi vimeoApi; + //TODO: In the future this will be stored in a hash table to provide batch uploading + private string file; + private string vimeo_url; + private FileInfo fileInfo; //Public members @@ -30,51 +36,57 @@ private void Start() { this.hideFlags = HideFlags.HideInInspector; } - public IEnumerator Init(string _file, string _token, int _maxChunkSize = 1000) + + public void Init(string _token, int _maxChunkSize = 1000) { + //A queue of video chunks to upload myChunks = new Queue(); - maxChunkSize = _maxChunkSize; - FileInfo fileInfo = new FileInfo(_file); - Debug.Log("File size in bytes" + fileInfo.Length.ToString()); - string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileInfo.Length.ToString() + "\" } }"; - using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) + //Instantiate the Vimeo Api + if (vimeoApi == null) { - UnityWebRequest videoResource = PrepareTusResourceRequest(request, _token); + vimeoApi = gameObject.AddComponent(); + vimeoApi.OnError += ApiError; + vimeoApi.OnNetworkError += NetworkError; + vimeoApi.OnRequestComplete += RequestComplete; - yield return VimeoApi.SendRequest(videoResource); - - if (videoResource.isNetworkError || videoResource.isHttpError) - { - if (OnUploadError != null) - { - OnUploadError(videoResource.error + " error code is: " + videoResource.responseCode); - } - } - else - { + vimeoApi.token = _token; + } - string tusUploadLink = GetTusUploadLink(videoResource); + maxChunkSize = _maxChunkSize; - CreateChunks(_file, fileInfo, tusUploadLink); - } - } + } + private void RequestComplete(string response) + { + string tusUploadLink = GetTusUploadLink(response); + vimeo_url = GetVideoPermlink(response); + CreateChunks(file, fileInfo, tusUploadLink); + //Kick off first chunks, others will be called on OnCompleteChunk() + VideoChunk firstChunk = myChunks.Dequeue(); + firstChunk.Upload(); } public void SetChunkSize(int size) { maxChunkSize = size; } + private void ApiError(string response) + { - public void Upload() + } + private void NetworkError(string response) { - //Kick off the first chunk, currently will call other chunks via the OnCompleteChunk event - if (OnUploadProgress != null) - { - OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); - } - VideoChunk firstChunk = myChunks.Dequeue(); - firstChunk.Upload(); + + } + public void Upload(string _file) + { + file = _file; + fileInfo = new FileInfo(_file); + + //Send the request, response will be catched in the RequestComplete() method + StartCoroutine( + vimeoApi.RequestTusResource("me/videos", fileInfo.Length) + ); } private void OnCompleteChunk(VideoChunk chunk, string msg) @@ -92,10 +104,11 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) if (myChunks.Count != 0) { VideoChunk nextChunk = myChunks.Dequeue(); - // OnUploadProgress("Uploading", (float)numChunks / myChunks.Count); + float progres = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; + OnUploadProgress("Uploading", progres); + Debug.Log(progres); nextChunk.Upload(); - } - else + } else { //Set the progress back to 0 if (OnUploadProgress != null) @@ -105,7 +118,7 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) //Emit upload complete if (OnUploadComplete != null) { - OnUploadComplete("Completed upload!"); + OnUploadComplete(vimeo_url); } } } @@ -134,8 +147,7 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi int remainder = (int)fileInfo.Length - (maxChunkSize * i); Debug.Log("Created last chunk and the remainder is: " + remainder); chunk.Init(indexByte, tusUploadLink, filePath, remainder); - } - else + } else { chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); } @@ -160,10 +172,15 @@ private UnityWebRequest PrepareTusResourceRequest(UnityWebRequest req, string to return req; } - private string GetTusUploadLink(UnityWebRequest response) + private string GetTusUploadLink(string response) { - JSONNode rawJSON = JSON.Parse(response.downloadHandler.text); + JSONNode rawJSON = JSON.Parse(response); return rawJSON["upload"]["upload_link"].Value; } + private string GetVideoPermlink(string response) + { + JSONNode rawJSON = JSON.Parse(response); + return rawJSON["link"].Value; + } } } \ No newline at end of file From bb82d0c64bcb4652991dcf76d1ea69c0af40c4e1 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 5 Oct 2018 18:08:26 -0400 Subject: [PATCH 13/68] Style formatting for all changed files --- .../Vimeo/Scripts/Recorder/EncoderManager.cs | 52 ++----- .../Scripts/Recorder/RecorderController.cs | 68 +++------ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 66 +++------ .../Vimeo/Scripts/Recorder/VimeoRecorder.cs | 15 +- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 129 ++++++------------ .../Vimeo/Scripts/Services/VimeoUploader.cs | 30 ++-- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 13 +- 7 files changed, 120 insertions(+), 253 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs b/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs index c674220e..5bd689e5 100644 --- a/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs +++ b/Assets/Vimeo/Scripts/Recorder/EncoderManager.cs @@ -35,17 +35,14 @@ public void Init(VimeoRecorder r) { _recorder = r; - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder = gameObject.AddComponent(); _vimeoEncoder.Init(_recorder); #else Debug.LogError("[Vimeo] Recording is only avaialabe in 2017.2 or higher."); #endif - } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) - { + } else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { #if VIMEO_AVPRO_CAPTURE_SUPPORT _avproEncoder = r.avproEncoder; #endif @@ -56,14 +53,11 @@ public void BeginRecording() { isRecording = true; - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder.BeginRecording(); #endif - } - else - { + } else { #if VIMEO_AVPRO_CAPTURE_SUPPORT _avproEncoder.StartCapture(); #endif @@ -74,14 +68,11 @@ public void EndRecording() { isRecording = false; - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { #if MEDIA_ENCODER_SUPPORT _vimeoEncoder.EndRecording(); #endif - } - else - { + } else { #if VIMEO_AVPRO_CAPTURE_SUPPORT // _avproEncoder.StartCapture(); #endif @@ -97,12 +88,9 @@ public void CancelRecording() public void AddFrame() { #if MEDIA_ENCODER_SUPPORT - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { _vimeoEncoder.AddFrame(); - } - else - { + } else { Debug.LogWarning("[VimeoRecorder] AddFrame is only available for MediaEncoder."); } #endif @@ -110,14 +98,11 @@ public void AddFrame() public string GetVideoFilePath() { - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { #if MEDIA_ENCODER_SUPPORT return _vimeoEncoder.encodedFilePath; #endif - } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) - { + } else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { #if VIMEO_AVPRO_CAPTURE_SUPPORT return _avproEncoder.LastFilePath; #endif @@ -128,14 +113,11 @@ public string GetVideoFilePath() public int GetCurrentFrame() { - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { #if MEDIA_ENCODER_SUPPORT return _vimeoEncoder.currentFrame; #endif - } - else if (_recorder.encoderType == EncoderType.AVProMovieCapture) - { + } else if (_recorder.encoderType == EncoderType.AVProMovieCapture) { #if VIMEO_AVPRO_CAPTURE_SUPPORT Debug.LogWarning("[VimeoRecorder] GetCurrentFrame not supported for AVProMovieCapture"); return -1; @@ -173,12 +155,9 @@ public void DeleteVideoFile() public void ManualFrameCapture() { #if MEDIA_ENCODER_SUPPORT - if (_recorder.encoderType == EncoderType.MediaEncoder) - { + if (_recorder.encoderType == EncoderType.MediaEncoder) { _vimeoEncoder.manualFrameCapture = true; - } - else - { + } else { Debug.LogWarning("[VimeoRecorder] ManualFrameCapture is only available for MediaEncoder."); } #endif @@ -187,8 +166,7 @@ public void ManualFrameCapture() void OnDestroy() { #if MEDIA_ENCODER_SUPPORT - if (_vimeoEncoder != null) - { + if (_vimeoEncoder != null) { Destroy(_vimeoEncoder); } #endif diff --git a/Assets/Vimeo/Scripts/Recorder/RecorderController.cs b/Assets/Vimeo/Scripts/Recorder/RecorderController.cs index c6290715..e4a71666 100644 --- a/Assets/Vimeo/Scripts/Recorder/RecorderController.cs +++ b/Assets/Vimeo/Scripts/Recorder/RecorderController.cs @@ -65,12 +65,9 @@ private void BeginMediaEncoderRecording() { InitInputs(); - if (recorder.realTime) - { + if (recorder.realTime) { Application.targetFrameRate = recorder.frameRate; - } - else - { + } else { Time.captureFramerate = recorder.frameRate; } @@ -101,22 +98,18 @@ private void BeginMediaEncoderRecording() encodedFilePath = Path.Combine(outputPath, GetFileName()); Debug.Log("[VimeoRecorder] Recording to " + GetFileName()); - if (!recorder.realTime) - { + if (!recorder.realTime) { recorder.recordAudio = false; } - if (recorder.recordAudio) - { + if (recorder.recordAudio) { #if UNITY_2018_1_OR_NEWER audioInput.BeginRecording(); encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs, audioAttrs); #else encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs); #endif - } - else - { + } else { encoder = new UnityEditor.Media.MediaEncoder(encodedFilePath, videoAttrs); } } @@ -130,21 +123,18 @@ public string GetFileName() public void EndRecording() { - if (encoder != null) - { + if (encoder != null) { encoder.Dispose(); encoder = null; } - if (videoInput != null) - { + if (videoInput != null) { videoInput.EndRecording(); Release(videoInput); } #if UNITY_2018_1_OR_NEWER - if (audioInput != null) - { + if (audioInput != null) { if (recorder.recordAudio) audioInput.EndRecording(); Release(audioInput); } @@ -163,22 +153,19 @@ public void DeleteVideoFile() IEnumerator RecordFrame() { yield return new WaitForEndOfFrame(); - if (!manualFrameCapture) - { + if (!manualFrameCapture) { AddFrame(); } } public void AddFrame() { - if (encoder != null && isRecording) - { + if (encoder != null && isRecording) { encoder.AddFrame(videoInput.GetFrame() as Texture2D); videoInput.EndFrame(); #if UNITY_2018_1_OR_NEWER - if (recorder.recordAudio) - { + if (recorder.recordAudio) { audioInput.StartFrame(); encoder.AddSamples(audioInput.GetBuffer()); audioInput.EndFrame(); @@ -191,21 +178,14 @@ public void AddFrame() public void LateUpdate() { - if (encoder != null && isRecording) - { - if (recorder.recordMode == RecordMode.Duration) - { - if (currentFrame > recorder.frameRate * recorder.recordDuration) - { + if (encoder != null && isRecording) { + if (recorder.recordMode == RecordMode.Duration) { + if (currentFrame > recorder.frameRate * recorder.recordDuration) { recorder.EndRecording(); - } - else - { + } else { StartCoroutine(RecordFrame()); } - } - else - { + } else { StartCoroutine(RecordFrame()); } } @@ -213,14 +193,12 @@ public void LateUpdate() private void InitInputs() { - if (videoInput != null) - { + if (videoInput != null) { Release(videoInput); } #if UNITY_2018_1_OR_NEWER - if (audioInput != null) - { + if (audioInput != null) { Release(audioInput); } @@ -229,8 +207,7 @@ private void InitInputs() audioInput.recorder = recorder; #endif - switch (recorder.defaultVideoInput) - { + switch (recorder.defaultVideoInput) { case VideoInputType.Screen: videoInput = gameObject.AddComponent(); break; @@ -255,12 +232,9 @@ void OnDestroy() public void Release(MonoBehaviour obj) { - if (Application.isEditor) - { + if (Application.isEditor) { DestroyImmediate(obj); - } - else - { + } else { Destroy(obj); } } diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index d62baec0..0b5617b5 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -29,8 +29,7 @@ public void Init(VimeoRecorder _recorder) { recorder = _recorder; - if (vimeoUploader == null) - { + if (vimeoUploader == null) { vimeoUploader = gameObject.AddComponent(); vimeoUploader.Init(recorder.GetVimeoToken()); @@ -42,14 +41,10 @@ public void Init(VimeoRecorder _recorder) public string GetVimeoPermalink() { - if (recorder.videoPermalink != null) - { - if (recorder.defaultShareLink == LinkType.ReviewPage) - { + if (recorder.videoPermalink != null) { + if (recorder.defaultShareLink == LinkType.ReviewPage) { return recorder.videoReviewPermalink; - } - else - { + } else { return recorder.videoPermalink; } } @@ -64,8 +59,7 @@ public void PublishVideo(string filename) } void UploadProgress(string status, float progress) { - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress(status, progress); } } @@ -77,23 +71,20 @@ void UploadComplete(string video_uri, float number) video = new VimeoVideo("", video_uri); #if UNITY_2018_1_OR_NEWER - if (recorder.defaultVideoInput == VideoInputType.Camera360) - { + if (recorder.defaultVideoInput == VideoInputType.Camera360) { vimeoUploader.vimeoApi.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); } #endif vimeoUploader.vimeoApi.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); - if (recorder.enableDownloads == false) - { + if (recorder.enableDownloads == false) { vimeoUploader.vimeoApi.SetVideoDownload(recorder.enableDownloads); } vimeoUploader.vimeoApi.SetVideoComments(recorder.commentMode); vimeoUploader.vimeoApi.SetVideoReviewPage(recorder.enableReviewPage); SetVideoName(recorder.GetVideoName()); - if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) - { + if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { vimeoUploader.vimeoApi.SetVideoPassword(recorder.videoPassword); } SetVideoPrivacyMode(recorder.privacyMode); @@ -105,13 +96,11 @@ private void VideoUpdated(string response) recorder.videoPermalink = json["link"]; recorder.videoReviewPermalink = json["review_link"]; - if (recorder.openInBrowser == true) - { + if (recorder.openInBrowser == true) { OpenVideo(); } - if (recorder.currentFolder != null && recorder.currentFolder.uri != null) - { + if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { vimeoUploader.vimeoApi.AddVideoToFolder(video, recorder.currentFolder); } @@ -120,8 +109,7 @@ private void VideoUpdated(string response) private void NetworkError(string error_message) { - if (OnNetworkError != null) - { + if (OnNetworkError != null) { OnNetworkError("It seems like you are not connected to the internet or are having connection problems."); } } @@ -130,30 +118,20 @@ private void ApiError(string response) { JSONNode json = JSON.Parse(response); - if (json["invalid_parameters"] != null) - { + if (json["invalid_parameters"] != null) { - for (int i = 0; i < json["invalid_parameters"].Count; i++) - { + for (int i = 0; i < json["invalid_parameters"].Count; i++) { // TODO use .Value - if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.download\"") - { - if (OnNetworkError != null) - { + if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.download\"") { + if (OnNetworkError != null) { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } - } - else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") - { - if (OnNetworkError != null) - { + } else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") { + if (OnNetworkError != null) { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } - } - else - { - if (OnNetworkError != null) - { + } else { + if (OnNetworkError != null) { OnNetworkError(json["invalid_parameters"][i]["field"] + ": " + json["invalid_parameters"][i]["error"]); } } @@ -165,8 +143,7 @@ private void ApiError(string response) public void SetVideoName(string title) { - if (title != null && title != "") - { + if (title != null && title != "") { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } // DRY vimeoUploader.vimeoApi.SetVideoName(title); saveCoroutine = StartCoroutine("SaveVideo"); @@ -184,8 +161,7 @@ private IEnumerator SaveVideo() { yield return new WaitForSeconds(1f); - if (video != null) - { + if (video != null) { vimeoUploader.vimeoApi.SaveVideo(video); } } diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index 449b38fc..44a3fac4 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -8,7 +8,7 @@ namespace Vimeo.Recorder { [AddComponentMenu("Video/Vimeo Recorder")] [HelpURL("https://github.com/vimeo/vimeo-unity-sdk")] - public class VimeoRecorder : RecorderSettings + public class VimeoRecorder : RecorderSettings { public delegate void RecordAction(); public event RecordAction OnUploadComplete; @@ -19,18 +19,18 @@ public class VimeoRecorder : RecorderSettings public bool isUploading = false; public float uploadProgress = 0; - public void Start() + public void Start() { if (encoder == null) { encoder = gameObject.AddComponent(); encoder.Init(this); } - + if (recordOnStart) { BeginRecording(); } } - + public void BeginRecording() { if (!isRecording) { @@ -57,7 +57,7 @@ public void EndRecording() Debug.Log("[Vimeo] Video did not automatically upload. VimeoPlayer.autoUpload is set to false."); } } - + public void CancelRecording() { isRecording = false; @@ -79,7 +79,7 @@ public void PublishVideo() publisher.OnUploadProgress += UploadProgress; publisher.OnNetworkError += NetworkError; } - + publisher.PublishVideo(encoder.GetVideoFilePath()); } @@ -97,7 +97,8 @@ private void UploadProgress(string status, float progress) } } - private void NetworkError(string status){ + private void NetworkError(string status) + { Debug.LogError(status); } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index f1e0db05..6268a532 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -74,8 +74,7 @@ public void GetUserFolders() public void AddVideoToFolder(VimeoVideo video, VimeoFolder folder) { - if (folder.id > 0 && video.uri != null) - { + if (folder.id > 0 && video.uri != null) { IEnumerator coroutine = Put("/me/folders/" + folder.id + "/videos?uris=" + video.uri); StartCoroutine(coroutine); } @@ -93,8 +92,7 @@ public void GetVideosInFolder(VimeoFolder folder, string fields = "name,uri") public void SetVideoViewPrivacy(PrivacyModeDisplay mode) { - switch (mode) - { + switch (mode) { case PrivacyModeDisplay.Anyone: form.AddField("privacy.view", VimeoApi.PrivacyMode.anybody.ToString()); @@ -120,8 +118,7 @@ public void SetVideoViewPrivacy(PrivacyModeDisplay mode) public void SetVideoComments(CommentMode mode) { - switch (mode) - { + switch (mode) { case CommentMode.Anyone: form.AddField("privacy.comments", "anybody"); break; @@ -180,36 +177,27 @@ public void UploadVideoFile(string file_path) IEnumerator GetTicket() { - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress("Authorizing", 0); } WWWForm form = new WWWForm(); form.AddField("type", "streaming"); - using (UnityWebRequest request = UnityWebRequest.Post(API_URL + "/me/videos", form)) - { + using (UnityWebRequest request = UnityWebRequest.Post(API_URL + "/me/videos", form)) { PrepareHeaders(request, "3.2"); yield return VimeoApi.SendRequest(request); - if (IsNetworkError(request)) - { - if (OnNetworkError != null) - { + if (IsNetworkError(request)) { + if (OnNetworkError != null) { OnNetworkError(request.error); } - } - else - { + } else { VimeoTicket ticket = VimeoTicket.CreateFromJSON(request.downloadHandler.text); - if (ticket.error == null) - { + if (ticket.error == null) { StartCoroutine(UploadVideo(ticket)); - } - else - { + } else { Debug.LogError(ticket.error + " " + ticket.developer_message); } } @@ -218,8 +206,7 @@ IEnumerator GetTicket() IEnumerator UploadVideo(VimeoTicket ticket) { - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress("Uploading", 0); } @@ -233,8 +220,7 @@ IEnumerator UploadVideo(VimeoTicket ticket) // Get local video file and store it in a byte array for uploading data = File.ReadAllBytes(video_file_path); success = true; - } - catch (IOException e) { + } catch (IOException e) { // TODO: fix this ugly code! Debug.Log("File is being accessed by another process. " + e.Message); } @@ -245,7 +231,7 @@ IEnumerator UploadVideo(VimeoTicket ticket) // Upload to the Vimeo server using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { uploader = request; - request.chunkedTransfer = false; + request.chunkedTransfer = false; request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); yield return VimeoApi.SendRequest(request); @@ -255,8 +241,7 @@ IEnumerator UploadVideo(VimeoTicket ticket) if (OnNetworkError != null) { OnNetworkError(request.error); } - } - else { + } else { StartCoroutine(VerifyUpload(ticket)); } } @@ -264,25 +249,20 @@ IEnumerator UploadVideo(VimeoTicket ticket) IEnumerator VerifyUpload(VimeoTicket ticket) { - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress("Verifying", 0.9999999f); } byte[] data = new byte[] { 0x00 }; - using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) - { + using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { request.chunkedTransfer = false; request.SetRequestHeader("Content-Range", "bytes */*"); yield return VimeoApi.SendRequest(request); - if (request.responseCode == 308) - { + if (request.responseCode == 308) { StartCoroutine(CompleteUpload(ticket)); - } - else - { + } else { Debug.Log(request.responseCode); } } @@ -290,18 +270,15 @@ IEnumerator VerifyUpload(VimeoTicket ticket) public IEnumerator CompleteUpload(VimeoTicket ticket) { - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress("Complete", 1f); } - using (UnityWebRequest request = UnityWebRequest.Delete(API_URL + ticket.complete_uri)) - { + using (UnityWebRequest request = UnityWebRequest.Delete(API_URL + ticket.complete_uri)) { PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (OnUploadComplete != null) - { + if (OnUploadComplete != null) { OnUploadComplete(request.GetResponseHeader("Location")); } } @@ -309,8 +286,7 @@ public IEnumerator CompleteUpload(VimeoTicket ticket) public IEnumerator Patch(string url) { - using (UnityWebRequest request = UnityWebRequest.Post(url, form)) - { + using (UnityWebRequest request = UnityWebRequest.Post(url, form)) { PrepareHeaders(request); request.SetRequestHeader("X-HTTP-Method-Override", "PATCH"); yield return VimeoApi.SendRequest(request); @@ -318,13 +294,10 @@ public IEnumerator Patch(string url) // Reset the form form = new WWWForm(); - if (request.responseCode != 200) - { + if (request.responseCode != 200) { Debug.LogError(request.downloadHandler.text); if (OnError != null) OnError(request.downloadHandler.text); - } - else if (OnPatchComplete != null) - { + } else if (OnPatchComplete != null) { OnPatchComplete(request.downloadHandler.text); } } @@ -333,24 +306,18 @@ public IEnumerator RequestTusResource(string api_path, long fileByteCount) { string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileByteCount.ToString() + "\" } }"; - if (token != null) - { - using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) - { + if (token != null) { + using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { PrepareTusHeaders(request); yield return VimeoApi.SendRequest(request); - if (request.error != null) - { + if (request.error != null) { Debug.Log(request.error); Debug.Log(request.responseCode); Debug.LogError(request.downloadHandler.text); if (OnError != null) OnError(request.downloadHandler.text); - } - else - { - if (OnRequestComplete != null) - { + } else { + if (OnRequestComplete != null) { OnRequestComplete(request.downloadHandler.text); } } @@ -359,23 +326,17 @@ public IEnumerator RequestTusResource(string api_path, long fileByteCount) } IEnumerator Put(string api_path) { - if (token != null) - { + if (token != null) { byte[] data = new byte[] { 0x00 }; - using (UnityWebRequest request = UnityWebRequest.Put(API_URL + api_path, data)) - { + using (UnityWebRequest request = UnityWebRequest.Put(API_URL + api_path, data)) { PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (request.error != null) - { + if (request.error != null) { Debug.LogError(request.downloadHandler.text); if (OnError != null) OnError(request.downloadHandler.text); - } - else - { - if (OnRequestComplete != null) - { + } else { + if (OnRequestComplete != null) { OnRequestComplete(request.downloadHandler.text); } } @@ -385,31 +346,24 @@ IEnumerator Put(string api_path) public IEnumerator Request(string api_path) { - if (token != null) - { + if (token != null) { UnityWebRequest request = UnityWebRequest.Get(API_URL + api_path); PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - if (request.responseCode != 200) - { - if (request.responseCode == 401) - { + if (request.responseCode != 200) { + if (request.responseCode == 401) { Debug.LogError("[VimeoApi] 401 Unauthorized request."); } - if (OnNetworkError != null && IsNetworkError(request)) - { + if (OnNetworkError != null && IsNetworkError(request)) { OnNetworkError(request.error); } - if (OnError != null && !IsNetworkError(request)) - { + if (OnError != null && !IsNetworkError(request)) { OnError(request.downloadHandler.text); } - } - else if (OnRequestComplete != null) - { + } else if (OnRequestComplete != null) { OnRequestComplete(request.downloadHandler.text); } } @@ -449,8 +403,7 @@ public static AsyncOperation SendRequest(UnityWebRequest req) void FixedUpdate() { - if (OnUploadProgress != null && uploader != null && uploader.uploadProgress != 1) - { + if (OnUploadProgress != null && uploader != null && uploader.uploadProgress != 1) { OnUploadProgress("Uploading", uploader.uploadProgress); } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index be15d4e6..a6523020 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -43,8 +43,7 @@ public void Init(string _token, int _maxChunkSize = 1000) myChunks = new Queue(); //Instantiate the Vimeo Api - if (vimeoApi == null) - { + if (vimeoApi == null) { vimeoApi = gameObject.AddComponent(); vimeoApi.OnError += ApiError; vimeoApi.OnNetworkError += NetworkError; @@ -92,8 +91,7 @@ public void Upload(string _file) private void OnCompleteChunk(VideoChunk chunk, string msg) { //Emit the event - if (OnChunckUploadComplete != null) - { + if (OnChunckUploadComplete != null) { OnChunckUploadComplete(chunk, msg); } @@ -101,23 +99,19 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) Destroy(chunk); //Make sure the queue is not empty - if (myChunks.Count != 0) - { + if (myChunks.Count != 0) { VideoChunk nextChunk = myChunks.Dequeue(); float progres = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; OnUploadProgress("Uploading", progres); Debug.Log(progres); nextChunk.Upload(); - } else - { + } else { //Set the progress back to 0 - if (OnUploadProgress != null) - { + if (OnUploadProgress != null) { OnUploadProgress("Idle", 0.0f); } //Emit upload complete - if (OnUploadComplete != null) - { + if (OnUploadComplete != null) { OnUploadComplete(vimeo_url); } } @@ -125,8 +119,7 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) private void OnChunkError(VideoChunk chunk, string err) { - if (OnChunckUploadError != null) - { + if (OnChunckUploadError != null) { OnChunckUploadError(chunk, err); } } @@ -135,20 +128,17 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi //Create the chunks numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); - for (int i = 0; i < numChunks; i++) - { + for (int i = 0; i < numChunks; i++) { int indexByte = maxChunkSize * i; VideoChunk chunk = this.gameObject.AddComponent(); chunk.hideFlags = HideFlags.HideInInspector; //If we are at the last chunk set the max chunk size to the fractional remainder - if (i + 1 == numChunks) - { + if (i + 1 == numChunks) { int remainder = (int)fileInfo.Length - (maxChunkSize * i); Debug.Log("Created last chunk and the remainder is: " + remainder); chunk.Init(indexByte, tusUploadLink, filePath, remainder); - } else - { + } else { chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); } diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index f6792f7c..387c5ee8 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -30,8 +30,7 @@ public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize private void ReadBytes() { - using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) - { + using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) { reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } @@ -45,8 +44,7 @@ private void DisposeBytes() private IEnumerator SendTusRequest() { ReadBytes(); - using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) - { + using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) { uploadRequest.chunkedTransfer = false; uploadRequest.method = "PATCH"; uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); @@ -55,13 +53,10 @@ private IEnumerator SendTusRequest() yield return VimeoApi.SendRequest(uploadRequest); - if (uploadRequest.isNetworkError || uploadRequest.isHttpError) - { + if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; OnChunckUploadError(this, concatErr); - } - else - { + } else { OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); } } From 741a516d1ff1fe6336667c4d6b5d93e43ea5e54d Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 15 Oct 2018 14:57:58 -0400 Subject: [PATCH 14/68] Implementing the missing events for the VimeoUploader --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 16 +++++------ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 2 ++ Assets/Vimeo/Scripts/Services/VimeoApi.cs | 7 ++--- .../Vimeo/Scripts/Services/VimeoUploader.cs | 28 ++++++++++++------- 4 files changed, 30 insertions(+), 23 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 40aeccd7..341cda69 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -48,7 +48,7 @@ public void _Before() recorder.defaultResolution = Vimeo.Recorder.Resolution.x540p; recorder.realTime = true; recorder.recordMode = RecordMode.Duration; - recorder.recordDuration = 5; + recorder.recordDuration = 1; recorder.privacyMode = VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink; recorder.openInBrowser = false; @@ -59,6 +59,7 @@ public void _Before() } [UnityTest] + [Timeout(100000000)] public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() { recorder.videoName = "Screen Test " + recorder.videoName; @@ -68,13 +69,12 @@ public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() recorder.OnUploadComplete += UploadComplete; - while (!uploaded) { - yield return new WaitForSeconds(.25f); - TimeoutCheck(); - } + yield return new WaitUntil(()=> uploaded); + Assert.IsTrue(uploaded); } [UnityTest] + [Timeout(100000000)] public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() { recorder.videoName = "MainCamera Test " + recorder.videoName; @@ -84,10 +84,8 @@ public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() recorder.OnUploadComplete += UploadComplete; - while (!uploaded) { - yield return new WaitForSeconds(.25f); - TimeoutCheck(); - } + yield return new WaitUntil(()=> uploaded); + Assert.IsTrue(uploaded); } private void TimeoutCheck(string msg = "Test timed out") diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 0b5617b5..425a2b75 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -36,6 +36,8 @@ public void Init(VimeoRecorder _recorder) vimeoUploader.vimeoApi.OnPatchComplete += VideoUpdated; vimeoUploader.OnUploadProgress += UploadProgress; vimeoUploader.OnUploadComplete += UploadComplete; + vimeoUploader.OnNetworkError += NetworkError; + vimeoUploader.OnApiError += ApiError; } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 6268a532..fa4cd332 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -312,10 +312,9 @@ public IEnumerator RequestTusResource(string api_path, long fileByteCount) yield return VimeoApi.SendRequest(request); if (request.error != null) { - Debug.Log(request.error); - Debug.Log(request.responseCode); - Debug.LogError(request.downloadHandler.text); - if (OnError != null) OnError(request.downloadHandler.text); + if (OnError != null) { + OnError(request.downloadHandler.text); + } } else { if (OnRequestComplete != null) { OnRequestComplete(request.downloadHandler.text); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index a6523020..4f1fc3bf 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Threading; using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -11,9 +12,11 @@ namespace Vimeo class VimeoUploader : MonoBehaviour { //Events + public delegate void ErrorAction(string response); + public event ErrorAction OnApiError; + public event ErrorAction OnNetworkError; public delegate void UploadAction(string status, float progress = 0.0f); public event UploadAction OnUploadProgress; - public event UploadAction OnUploadError; public event UploadAction OnUploadComplete; public delegate void UploadEvent(VideoChunk chunk, string msg = ""); @@ -23,13 +26,14 @@ class VimeoUploader : MonoBehaviour //Private members private Queue myChunks; public VimeoApi vimeoApi; - //TODO: In the future this will be stored in a hash table to provide batch uploading + //TODO: In the future this will be stored in a list to provide batch uploading private string file; private string vimeo_url; private FileInfo fileInfo; //Public members + public int concurentChunks = 4; public int maxChunkSize; public int numChunks; private void Start() @@ -37,7 +41,7 @@ private void Start() this.hideFlags = HideFlags.HideInInspector; } - public void Init(string _token, int _maxChunkSize = 1000) + public void Init(string _token, int _maxChunkSize = 10000) { //A queue of video chunks to upload myChunks = new Queue(); @@ -55,28 +59,32 @@ public void Init(string _token, int _maxChunkSize = 1000) maxChunkSize = _maxChunkSize; } + private void RequestComplete(string response) { string tusUploadLink = GetTusUploadLink(response); vimeo_url = GetVideoPermlink(response); CreateChunks(file, fileInfo, tusUploadLink); - //Kick off first chunks, others will be called on OnCompleteChunk() + VideoChunk firstChunk = myChunks.Dequeue(); firstChunk.Upload(); } + public void SetChunkSize(int size) { maxChunkSize = size; } + private void ApiError(string response) { - + OnApiError(response); } private void NetworkError(string response) { - + OnNetworkError(response); } + public void Upload(string _file) { file = _file; @@ -100,11 +108,12 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) //Make sure the queue is not empty if (myChunks.Count != 0) { - VideoChunk nextChunk = myChunks.Dequeue(); + VideoChunk currentChunk = myChunks.Dequeue(); + float progres = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; OnUploadProgress("Uploading", progres); - Debug.Log(progres); - nextChunk.Upload(); + + currentChunk.Upload(); } else { //Set the progress back to 0 if (OnUploadProgress != null) { @@ -136,7 +145,6 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi //If we are at the last chunk set the max chunk size to the fractional remainder if (i + 1 == numChunks) { int remainder = (int)fileInfo.Length - (maxChunkSize * i); - Debug.Log("Created last chunk and the remainder is: " + remainder); chunk.Init(indexByte, tusUploadLink, filePath, remainder); } else { chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); From fbdf947884d2578d5dae3635b49416712da6d353 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 16 Oct 2018 11:51:51 -0400 Subject: [PATCH 15/68] =?UTF-8?q?Changing=20the=20architecture=20so=20Vime?= =?UTF-8?q?oUploader=20extends=20the=20VimeoApi=20instead=20of=20storing?= =?UTF-8?q?=20a=20reference=20to=20it=20=F0=9F=99=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 28 ++++----- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 17 +++++- .../Vimeo/Scripts/Services/VimeoUploader.cs | 61 +++++-------------- 3 files changed, 44 insertions(+), 62 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 425a2b75..5e460db3 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -23,7 +23,7 @@ public class VimeoPublisher : MonoBehaviour private Coroutine saveCoroutine; private void Start() { - this.hideFlags = HideFlags.HideInInspector; + // this.hideFlags = HideFlags.HideInInspector; } public void Init(VimeoRecorder _recorder) { @@ -33,11 +33,11 @@ public void Init(VimeoRecorder _recorder) vimeoUploader = gameObject.AddComponent(); vimeoUploader.Init(recorder.GetVimeoToken()); - vimeoUploader.vimeoApi.OnPatchComplete += VideoUpdated; + vimeoUploader.OnPatchComplete += VideoUpdated; vimeoUploader.OnUploadProgress += UploadProgress; vimeoUploader.OnUploadComplete += UploadComplete; vimeoUploader.OnNetworkError += NetworkError; - vimeoUploader.OnApiError += ApiError; + vimeoUploader.OnError += ApiError; } } @@ -66,7 +66,7 @@ void UploadProgress(string status, float progress) } } - void UploadComplete(string video_uri, float number) + private void UploadComplete(string video_uri) { UploadProgress("SavingInfo", .999f); @@ -74,20 +74,20 @@ void UploadComplete(string video_uri, float number) #if UNITY_2018_1_OR_NEWER if (recorder.defaultVideoInput == VideoInputType.Camera360) { - vimeoUploader.vimeoApi.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); + vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); } #endif - vimeoUploader.vimeoApi.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); + vimeoUploader.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); if (recorder.enableDownloads == false) { - vimeoUploader.vimeoApi.SetVideoDownload(recorder.enableDownloads); + vimeoUploader.SetVideoDownload(recorder.enableDownloads); } - vimeoUploader.vimeoApi.SetVideoComments(recorder.commentMode); - vimeoUploader.vimeoApi.SetVideoReviewPage(recorder.enableReviewPage); + vimeoUploader.SetVideoComments(recorder.commentMode); + vimeoUploader.SetVideoReviewPage(recorder.enableReviewPage); SetVideoName(recorder.GetVideoName()); if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { - vimeoUploader.vimeoApi.SetVideoPassword(recorder.videoPassword); + vimeoUploader.SetVideoPassword(recorder.videoPassword); } SetVideoPrivacyMode(recorder.privacyMode); } @@ -103,7 +103,7 @@ private void VideoUpdated(string response) } if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { - vimeoUploader.vimeoApi.AddVideoToFolder(video, recorder.currentFolder); + vimeoUploader.AddVideoToFolder(video, recorder.currentFolder); } UploadProgress("SaveInfoComplete", 1f); @@ -147,7 +147,7 @@ public void SetVideoName(string title) { if (title != null && title != "") { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } // DRY - vimeoUploader.vimeoApi.SetVideoName(title); + vimeoUploader.SetVideoName(title); saveCoroutine = StartCoroutine("SaveVideo"); } } @@ -155,7 +155,7 @@ public void SetVideoName(string title) public void SetVideoPrivacyMode(VimeoApi.PrivacyModeDisplay mode) { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } - vimeoUploader.vimeoApi.SetVideoViewPrivacy(mode); + vimeoUploader.SetVideoViewPrivacy(mode); saveCoroutine = StartCoroutine("SaveVideo"); } @@ -164,7 +164,7 @@ private IEnumerator SaveVideo() yield return new WaitForSeconds(1f); if (video != null) { - vimeoUploader.vimeoApi.SaveVideo(video); + vimeoUploader.SaveVideo(video); } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index fa4cd332..f82ba3d9 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -1,5 +1,6 @@ using System.Xml; using System.IO; +using System; using System.Collections; using System.Collections.Generic; using System.Text; @@ -58,7 +59,13 @@ public enum CommentMode void Start() { - this.hideFlags = HideFlags.HideInInspector; + // this.hideFlags = HideFlags.HideInInspector; + form = new WWWForm(); + } + + protected void InitApi() + { + // this.hideFlags = HideFlags.HideInInspector; form = new WWWForm(); } @@ -382,6 +389,14 @@ private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); } + protected void TriggerDerivedOnProgress(string status, float progress){ + OnUploadProgress(status, progress); + } + + protected void TriggerDerivedOnComplete(string vimeo_uri){ + OnUploadComplete(vimeo_uri); + } + public static bool IsNetworkError(UnityWebRequest req) { #if UNITY_2017_1_OR_NEWER diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 4f1fc3bf..610ab925 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -9,16 +9,8 @@ namespace Vimeo { - class VimeoUploader : MonoBehaviour + class VimeoUploader : VimeoApi { - //Events - public delegate void ErrorAction(string response); - public event ErrorAction OnApiError; - public event ErrorAction OnNetworkError; - public delegate void UploadAction(string status, float progress = 0.0f); - public event UploadAction OnUploadProgress; - public event UploadAction OnUploadComplete; - public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; @@ -31,33 +23,23 @@ class VimeoUploader : MonoBehaviour private string vimeo_url; private FileInfo fileInfo; - //Public members public int concurentChunks = 4; public int maxChunkSize; public int numChunks; + private void Start() { - this.hideFlags = HideFlags.HideInInspector; + // this.hideFlags = HideFlags.HideInInspector; } - public void Init(string _token, int _maxChunkSize = 10000) + public void Init(string _token, int _maxChunkSize = 1000) { - //A queue of video chunks to upload myChunks = new Queue(); - - //Instantiate the Vimeo Api - if (vimeoApi == null) { - vimeoApi = gameObject.AddComponent(); - vimeoApi.OnError += ApiError; - vimeoApi.OnNetworkError += NetworkError; - vimeoApi.OnRequestComplete += RequestComplete; - - vimeoApi.token = _token; - } - + token = _token; + InitApi(); + OnRequestComplete += RequestComplete; maxChunkSize = _maxChunkSize; - } private void RequestComplete(string response) @@ -76,23 +58,14 @@ public void SetChunkSize(int size) maxChunkSize = size; } - private void ApiError(string response) - { - OnApiError(response); - } - private void NetworkError(string response) - { - OnNetworkError(response); - } - public void Upload(string _file) { file = _file; fileInfo = new FileInfo(_file); - + Debug.Log("I am here"); //Send the request, response will be catched in the RequestComplete() method StartCoroutine( - vimeoApi.RequestTusResource("me/videos", fileInfo.Length) + RequestTusResource("me/videos", fileInfo.Length) ); } @@ -111,18 +84,12 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) VideoChunk currentChunk = myChunks.Dequeue(); float progres = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; - OnUploadProgress("Uploading", progres); - + TriggerDerivedOnProgress("Uploading", progres); currentChunk.Upload(); } else { - //Set the progress back to 0 - if (OnUploadProgress != null) { - OnUploadProgress("Idle", 0.0f); - } - //Emit upload complete - if (OnUploadComplete != null) { - OnUploadComplete(vimeo_url); - } + TriggerDerivedOnProgress("Idle", 0.0f); + TriggerDerivedOnComplete(vimeo_url); + Debug.Log(vimeo_url); } } @@ -153,7 +120,7 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi //Register evenets chunk.OnChunckUploadComplete += OnCompleteChunk; chunk.OnChunckUploadError += OnChunkError; - + Debug.Log("Created chunk number: " + myChunks.Count); //Push it to the queue myChunks.Enqueue(chunk); From 4e0c4771491ce124857bf3d3fd5f0767b5bdd478 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 16 Oct 2018 12:29:12 -0400 Subject: [PATCH 16/68] Setting the video information right after a tus video resource has been created instead of at the end of an upload This resolved situation where an error in upload makes the video uploaded "Untitled" and public --- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 50 ++++++++++--------- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 21 +++++--- .../Vimeo/Scripts/Services/VimeoUploader.cs | 4 +- 3 files changed, 42 insertions(+), 33 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 5e460db3..f81cbbba 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -23,7 +23,7 @@ public class VimeoPublisher : MonoBehaviour private Coroutine saveCoroutine; private void Start() { - // this.hideFlags = HideFlags.HideInInspector; + this.hideFlags = HideFlags.HideInInspector; } public void Init(VimeoRecorder _recorder) { @@ -37,9 +37,34 @@ public void Init(VimeoRecorder _recorder) vimeoUploader.OnUploadProgress += UploadProgress; vimeoUploader.OnUploadComplete += UploadComplete; vimeoUploader.OnNetworkError += NetworkError; + vimeoUploader.OnRequestComplete += RequestComplete; vimeoUploader.OnError += ApiError; } } + private void RequestComplete(string response) + { + string video_uri = vimeoUploader.GetVideoPermlink(response); + video = new VimeoVideo("", video_uri); + +#if UNITY_2018_1_OR_NEWER + if (recorder.defaultVideoInput == VideoInputType.Camera360) { + vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); + } +#endif + + vimeoUploader.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); + if (recorder.enableDownloads == false) { + vimeoUploader.SetVideoDownload(recorder.enableDownloads); + } + vimeoUploader.SetVideoComments(recorder.commentMode); + vimeoUploader.SetVideoReviewPage(recorder.enableReviewPage); + SetVideoName(recorder.GetVideoName()); + + if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { + vimeoUploader.SetVideoPassword(recorder.videoPassword); + } + SetVideoPrivacyMode(recorder.privacyMode); + } public string GetVimeoPermalink() { @@ -68,28 +93,7 @@ void UploadProgress(string status, float progress) private void UploadComplete(string video_uri) { - UploadProgress("SavingInfo", .999f); - - video = new VimeoVideo("", video_uri); - -#if UNITY_2018_1_OR_NEWER - if (recorder.defaultVideoInput == VideoInputType.Camera360) { - vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); - } -#endif - - vimeoUploader.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); - if (recorder.enableDownloads == false) { - vimeoUploader.SetVideoDownload(recorder.enableDownloads); - } - vimeoUploader.SetVideoComments(recorder.commentMode); - vimeoUploader.SetVideoReviewPage(recorder.enableReviewPage); - SetVideoName(recorder.GetVideoName()); - - if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { - vimeoUploader.SetVideoPassword(recorder.videoPassword); - } - SetVideoPrivacyMode(recorder.privacyMode); + UploadProgress("Finalizing", .999f); } private void VideoUpdated(string response) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index f82ba3d9..1c8e9168 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -57,16 +57,15 @@ public enum CommentMode private UnityWebRequest uploader; - void Start() + private void Start() { - // this.hideFlags = HideFlags.HideInInspector; + this.hideFlags = HideFlags.HideInInspector; form = new WWWForm(); } protected void InitApi() { - // this.hideFlags = HideFlags.HideInInspector; - form = new WWWForm(); + Start(); } public void GetVideoFileUrlByVimeoId(int video_id, string fields = "name,uri,duration,width,height,spatial,play,description") @@ -389,12 +388,18 @@ private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); } - protected void TriggerDerivedOnProgress(string status, float progress){ - OnUploadProgress(status, progress); + protected void TriggerDerivedOnProgress(string status, float progress) + { + if (OnUploadProgress != null) { + OnUploadProgress(status, progress); + } } - protected void TriggerDerivedOnComplete(string vimeo_uri){ - OnUploadComplete(vimeo_uri); + protected void TriggerDerivedOnComplete(string vimeo_uri) + { + if (OnUploadComplete != null){ + OnUploadComplete(vimeo_uri); + } } public static bool IsNetworkError(UnityWebRequest req) diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 610ab925..98a69574 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -30,7 +30,7 @@ class VimeoUploader : VimeoApi private void Start() { - // this.hideFlags = HideFlags.HideInInspector; + this.hideFlags = HideFlags.HideInInspector; } public void Init(string _token, int _maxChunkSize = 1000) @@ -142,7 +142,7 @@ private string GetTusUploadLink(string response) JSONNode rawJSON = JSON.Parse(response); return rawJSON["upload"]["upload_link"].Value; } - private string GetVideoPermlink(string response) + public string GetVideoPermlink(string response) { JSONNode rawJSON = JSON.Parse(response); return rawJSON["link"].Value; From 2427d90deb58cbaf846728cff0a46aec75b7e04b Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 16 Oct 2018 13:54:04 -0400 Subject: [PATCH 17/68] Cleaning up the VimeoUploader refactor - Setting up the video (privacy/name/review page) at the begining of the upload - Implementing VimeoUplader as a derived class from the VimeoApi base class - Implementing events (OnUpload...) - Fixing typos (e.g progress in VimeoUploader) - Cleaning up whitespaces and comments - Fixing misc PR comments --- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 12 ++-- .../Vimeo/Scripts/Recorder/VimeoRecorder.cs | 2 +- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 4 +- .../Vimeo/Scripts/Services/VimeoUploader.cs | 65 +++++++------------ Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 15 ++--- 5 files changed, 40 insertions(+), 58 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index f81cbbba..714a8f6f 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -43,7 +43,7 @@ public void Init(VimeoRecorder _recorder) } private void RequestComplete(string response) { - string video_uri = vimeoUploader.GetVideoPermlink(response); + string video_uri = VimeoUploader.GetVideoPermlink(response); video = new VimeoVideo("", video_uri); #if UNITY_2018_1_OR_NEWER @@ -84,6 +84,7 @@ public void PublishVideo(string filename) Debug.Log("[VimeoRecorder] Uploading to Vimeo"); vimeoUploader.Upload(filename); } + void UploadProgress(string status, float progress) { if (OnUploadProgress != null) { @@ -93,7 +94,10 @@ void UploadProgress(string status, float progress) private void UploadComplete(string video_uri) { - UploadProgress("Finalizing", .999f); + if (recorder.openInBrowser == true) { + OpenVideo(); + } + Debug.Log("[VimeoPublisher] Published video to " + video_uri); } private void VideoUpdated(string response) @@ -102,10 +106,6 @@ private void VideoUpdated(string response) recorder.videoPermalink = json["link"]; recorder.videoReviewPermalink = json["review_link"]; - if (recorder.openInBrowser == true) { - OpenVideo(); - } - if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { vimeoUploader.AddVideoToFolder(video, recorder.currentFolder); } diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index 44a3fac4..2dd1e765 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -54,7 +54,7 @@ public void EndRecording() if (autoUpload) { PublishVideo(); } else { - Debug.Log("[Vimeo] Video did not automatically upload. VimeoPlayer.autoUpload is set to false."); + Debug.Log("[VimeoRecorder] Video did not automatically upload. VimeoRecorder.autoUpload is set to false."); } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 1c8e9168..f7bf29e4 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -375,11 +375,9 @@ public IEnumerator Request(string api_path) } private void PrepareTusHeaders(UnityWebRequest r, string apiVersion = "3.4") { - r.chunkedTransfer = false; r.method = "POST"; - r.SetRequestHeader("Authorization", "bearer " + token); r.SetRequestHeader("Content-Type", "application/json"); - r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); + PrepareHeaders(r, apiVersion); } private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") { diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 98a69574..491181d4 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -15,15 +15,10 @@ class VimeoUploader : VimeoApi public event UploadEvent OnChunckUploadComplete; public event UploadEvent OnChunckUploadError; - //Private members private Queue myChunks; - public VimeoApi vimeoApi; - //TODO: In the future this will be stored in a list to provide batch uploading private string file; private string vimeo_url; private FileInfo fileInfo; - - //Public members public int concurentChunks = 4; public int maxChunkSize; public int numChunks; @@ -44,7 +39,7 @@ public void Init(string _token, int _maxChunkSize = 1000) private void RequestComplete(string response) { - string tusUploadLink = GetTusUploadLink(response); + string tusUploadLink = VimeoUploader.GetTusUploadLink(response); vimeo_url = GetVideoPermlink(response); CreateChunks(file, fileInfo, tusUploadLink); @@ -62,11 +57,7 @@ public void Upload(string _file) { file = _file; fileInfo = new FileInfo(_file); - Debug.Log("I am here"); - //Send the request, response will be catched in the RequestComplete() method - StartCoroutine( - RequestTusResource("me/videos", fileInfo.Length) - ); + StartCoroutine(RequestTusResource("me/videos", fileInfo.Length)); } private void OnCompleteChunk(VideoChunk chunk, string msg) @@ -78,19 +69,9 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) //Destroy the chunk Destroy(chunk); - - //Make sure the queue is not empty - if (myChunks.Count != 0) { - VideoChunk currentChunk = myChunks.Dequeue(); - - float progres = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; - TriggerDerivedOnProgress("Uploading", progres); - currentChunk.Upload(); - } else { - TriggerDerivedOnProgress("Idle", 0.0f); - TriggerDerivedOnComplete(vimeo_url); - Debug.Log(vimeo_url); - } + + //And upload the next one + UploadNextChunk(); } private void OnChunkError(VideoChunk chunk, string err) @@ -99,6 +80,7 @@ private void OnChunkError(VideoChunk chunk, string err) OnChunckUploadError(chunk, err); } } + private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) { //Create the chunks @@ -117,32 +99,35 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); } - //Register evenets - chunk.OnChunckUploadComplete += OnCompleteChunk; - chunk.OnChunckUploadError += OnChunkError; - Debug.Log("Created chunk number: " + myChunks.Count); - //Push it to the queue + chunk.OnChunkUploadComplete += OnCompleteChunk; + chunk.OnChunkUploadError += OnChunkError; myChunks.Enqueue(chunk); } } - private UnityWebRequest PrepareTusResourceRequest(UnityWebRequest req, string token) + + private void UploadNextChunk() { - //Prep headers - req.chunkedTransfer = false; - req.method = "POST"; - req.SetRequestHeader("Authorization", "bearer " + token); - req.SetRequestHeader("Content-Type", "application/json"); - req.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); - - return req; + //Make sure the queue is not empty + if (myChunks.Count != 0) { + VideoChunk currentChunk = myChunks.Dequeue(); + + float progress = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; + TriggerDerivedOnProgress("Uploading", progress); + currentChunk.Upload(); + } else { + TriggerDerivedOnComplete(vimeo_url); + TriggerDerivedOnProgress("Idle", 0.0f); + } } - private string GetTusUploadLink(string response) + + private static string GetTusUploadLink(string response) { JSONNode rawJSON = JSON.Parse(response); return rawJSON["upload"]["upload_link"].Value; } - public string GetVideoPermlink(string response) + + public static string GetVideoPermlink(string response) { JSONNode rawJSON = JSON.Parse(response); return rawJSON["link"].Value; diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 387c5ee8..cd76fb66 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -14,15 +14,15 @@ class VideoChunk : MonoBehaviour private string url; private byte[] bytes; private string file_path; - private int chuckSize; + private int chunkSize; public delegate void UploadEvent(VideoChunk chunk, string msg = ""); - public event UploadEvent OnChunckUploadComplete; - public event UploadEvent OnChunckUploadError; + public event UploadEvent OnChunkUploadComplete; + public event UploadEvent OnChunkUploadError; - public void Init(int _indexByte, string _url, string _file_path, int _chucnkSize) + public void Init(int _indexByte, string _url, string _file_path, int _chunkSize) { - bytes = new byte[_chucnkSize]; + bytes = new byte[_chunkSize]; file_path = _file_path; indexByte = _indexByte; url = _url; @@ -54,10 +54,9 @@ private IEnumerator SendTusRequest() yield return VimeoApi.SendRequest(uploadRequest); if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { - string concatErr = "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode; - OnChunckUploadError(this, concatErr); + OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); } else { - OnChunckUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); + OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); } } DisposeBytes(); From 1be6de641bdd831fa837198bcf4a9bdca8557c16 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 11:49:34 -0400 Subject: [PATCH 18/68] Fixing the message sent on upload complete, and making sure the tests work properly --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 10 +++++----- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 6 +++--- Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs | 2 +- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 341cda69..8d1f22b5 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -48,7 +48,7 @@ public void _Before() recorder.defaultResolution = Vimeo.Recorder.Resolution.x540p; recorder.realTime = true; recorder.recordMode = RecordMode.Duration; - recorder.recordDuration = 1; + recorder.recordDuration = 5; recorder.privacyMode = VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink; recorder.openInBrowser = false; @@ -59,7 +59,7 @@ public void _Before() } [UnityTest] - [Timeout(100000000)] + [Timeout(300000)] public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() { recorder.videoName = "Screen Test " + recorder.videoName; @@ -69,12 +69,12 @@ public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() recorder.OnUploadComplete += UploadComplete; - yield return new WaitUntil(()=> uploaded); + yield return new WaitUntil(()=> uploaded == true); Assert.IsTrue(uploaded); } [UnityTest] - [Timeout(100000000)] + [Timeout(300000)] public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() { recorder.videoName = "MainCamera Test " + recorder.videoName; @@ -84,7 +84,7 @@ public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() recorder.OnUploadComplete += UploadComplete; - yield return new WaitUntil(()=> uploaded); + yield return new WaitUntil(()=> uploaded == true); Assert.IsTrue(uploaded); } diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 714a8f6f..75551804 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -97,6 +97,9 @@ private void UploadComplete(string video_uri) if (recorder.openInBrowser == true) { OpenVideo(); } + if (OnUploadProgress != null) { + OnUploadProgress("UploadComplete", 1f); + } Debug.Log("[VimeoPublisher] Published video to " + video_uri); } @@ -109,8 +112,6 @@ private void VideoUpdated(string response) if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { vimeoUploader.AddVideoToFolder(video, recorder.currentFolder); } - - UploadProgress("SaveInfoComplete", 1f); } private void NetworkError(string error_message) @@ -144,7 +145,6 @@ private void ApiError(string response) } } - UploadProgress("SaveInfoComplete", 1f); } public void SetVideoName(string title) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index 2dd1e765..3d6db478 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -87,7 +87,7 @@ private void UploadProgress(string status, float progress) { uploadProgress = progress; - if (status == "SaveInfoComplete") { + if (status == "UploadComplete") { isUploading = false; encoder.DeleteVideoFile(); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 491181d4..4a582b52 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -28,7 +28,7 @@ private void Start() this.hideFlags = HideFlags.HideInInspector; } - public void Init(string _token, int _maxChunkSize = 1000) + public void Init(string _token, int _maxChunkSize = 20000) { myChunks = new Queue(); token = _token; @@ -116,8 +116,8 @@ private void UploadNextChunk() TriggerDerivedOnProgress("Uploading", progress); currentChunk.Upload(); } else { + TriggerDerivedOnProgress("UploadComplete", 1f); TriggerDerivedOnComplete(vimeo_url); - TriggerDerivedOnProgress("Idle", 0.0f); } } From 6e9a08897622172f7acac5913a82c7f8a7123bfa Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 15:59:02 -0400 Subject: [PATCH 19/68] =?UTF-8?q?Deleting=20all=20legacy=20upload=20code?= =?UTF-8?q?=20from=20VimeoApi=20=F0=9F=9B=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 124 ---------------------- 1 file changed, 124 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index f7bf29e4..4b0169dc 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -55,8 +55,6 @@ public enum CommentMode public static string API_URL = "https://api.vimeo.com"; private WWWForm form; - private UnityWebRequest uploader; - private void Start() { this.hideFlags = HideFlags.HideInInspector; @@ -175,121 +173,6 @@ public void SaveVideo(VimeoVideo video) StartCoroutine(Patch(API_URL + "/videos/" + video.id)); } - public void UploadVideoFile(string file_path) - { - video_file_path = file_path; - StartCoroutine(GetTicket()); - } - - IEnumerator GetTicket() - { - if (OnUploadProgress != null) { - OnUploadProgress("Authorizing", 0); - } - - WWWForm form = new WWWForm(); - form.AddField("type", "streaming"); - - using (UnityWebRequest request = UnityWebRequest.Post(API_URL + "/me/videos", form)) { - PrepareHeaders(request, "3.2"); - yield return VimeoApi.SendRequest(request); - - if (IsNetworkError(request)) { - if (OnNetworkError != null) { - OnNetworkError(request.error); - } - } else { - VimeoTicket ticket = VimeoTicket.CreateFromJSON(request.downloadHandler.text); - - if (ticket.error == null) { - StartCoroutine(UploadVideo(ticket)); - } else { - Debug.LogError(ticket.error + " " + ticket.developer_message); - } - } - } - } - - IEnumerator UploadVideo(VimeoTicket ticket) - { - if (OnUploadProgress != null) { - OnUploadProgress("Uploading", 0); - } - - byte[] data = new byte[0]; - bool success = false; - - - // Using try/catch to wait for video to finish being - while (success == false) { - try { - // Get local video file and store it in a byte array for uploading - data = File.ReadAllBytes(video_file_path); - success = true; - } catch (IOException e) { - // TODO: fix this ugly code! - Debug.Log("File is being accessed by another process. " + e.Message); - } - } - - FileInfo video_file = new FileInfo(video_file_path); - - // Upload to the Vimeo server - using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { - uploader = request; - request.chunkedTransfer = false; - request.SetRequestHeader("Content-Type", "video/" + video_file.Extension); - yield return VimeoApi.SendRequest(request); - - uploader = null; - - if (IsNetworkError(request)) { - if (OnNetworkError != null) { - OnNetworkError(request.error); - } - } else { - StartCoroutine(VerifyUpload(ticket)); - } - } - } - - IEnumerator VerifyUpload(VimeoTicket ticket) - { - if (OnUploadProgress != null) { - OnUploadProgress("Verifying", 0.9999999f); - } - - byte[] data = new byte[] { 0x00 }; - - using (UnityWebRequest request = UnityWebRequest.Put(ticket.upload_link_secure, data)) { - request.chunkedTransfer = false; - request.SetRequestHeader("Content-Range", "bytes */*"); - yield return VimeoApi.SendRequest(request); - - if (request.responseCode == 308) { - StartCoroutine(CompleteUpload(ticket)); - } else { - Debug.Log(request.responseCode); - } - } - } - - public IEnumerator CompleteUpload(VimeoTicket ticket) - { - if (OnUploadProgress != null) { - OnUploadProgress("Complete", 1f); - } - - using (UnityWebRequest request = UnityWebRequest.Delete(API_URL + ticket.complete_uri)) { - PrepareHeaders(request); - yield return VimeoApi.SendRequest(request); - - if (OnUploadComplete != null) { - OnUploadComplete(request.GetResponseHeader("Location")); - } - } - } - public IEnumerator Patch(string url) { using (UnityWebRequest request = UnityWebRequest.Post(url, form)) { @@ -417,12 +300,5 @@ public static AsyncOperation SendRequest(UnityWebRequest req) return req.Send(); #endif } - - void FixedUpdate() - { - if (OnUploadProgress != null && uploader != null && uploader.uploadProgress != 1) { - OnUploadProgress("Uploading", uploader.uploadProgress); - } - } } } From cd23dcb576ace30a1d006a9054e68cf917f3fd13 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 16:07:20 -0400 Subject: [PATCH 20/68] Moving the OnUploadProgress and OnUploadComplete events from the Api to the Uploader class --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 20 ++---------------- .../Vimeo/Scripts/Services/VimeoUploader.cs | 21 +++++++++++++------ 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 4b0169dc..2c816826 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -40,14 +40,10 @@ public enum CommentMode public delegate void RequestAction(string response); public event RequestAction OnRequestComplete; - public event RequestAction OnUploadComplete; public event RequestAction OnPatchComplete; public event RequestAction OnError; public event RequestAction OnNetworkError; - public delegate void UploadAction(string status, float progress); - public event UploadAction OnUploadProgress; - private string video_file_path; [HideInInspector] @@ -256,12 +252,14 @@ public IEnumerator Request(string api_path) } } } + private void PrepareTusHeaders(UnityWebRequest r, string apiVersion = "3.4") { r.method = "POST"; r.SetRequestHeader("Content-Type", "application/json"); PrepareHeaders(r, apiVersion); } + private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") { r.chunkedTransfer = false; @@ -269,20 +267,6 @@ private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4") r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion); } - protected void TriggerDerivedOnProgress(string status, float progress) - { - if (OnUploadProgress != null) { - OnUploadProgress(status, progress); - } - } - - protected void TriggerDerivedOnComplete(string vimeo_uri) - { - if (OnUploadComplete != null){ - OnUploadComplete(vimeo_uri); - } - } - public static bool IsNetworkError(UnityWebRequest req) { #if UNITY_2017_1_OR_NEWER diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 4a582b52..0ce7eb45 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -11,9 +11,12 @@ namespace Vimeo { class VimeoUploader : VimeoApi { - public delegate void UploadEvent(VideoChunk chunk, string msg = ""); - public event UploadEvent OnChunckUploadComplete; - public event UploadEvent OnChunckUploadError; + public delegate void ChunkUploadEvent(VideoChunk chunk, string msg = ""); + public event ChunkUploadEvent OnChunckUploadComplete; + public event ChunkUploadEvent OnChunckUploadError; + public delegate void UploadAction(string status, float progress); + public event UploadAction OnUploadProgress; + public event RequestAction OnUploadComplete; private Queue myChunks; private string file; @@ -113,11 +116,17 @@ private void UploadNextChunk() VideoChunk currentChunk = myChunks.Dequeue(); float progress = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; - TriggerDerivedOnProgress("Uploading", progress); + if (OnUploadProgress != null) { + OnUploadProgress("Uploading", progress); + } currentChunk.Upload(); } else { - TriggerDerivedOnProgress("UploadComplete", 1f); - TriggerDerivedOnComplete(vimeo_url); + if (OnUploadProgress != null) { + OnUploadProgress("UploadComplete", 1f); + } + if (OnUploadComplete != null) { + OnUploadComplete(vimeo_url); + } } } From d684763673ba6efa0aaa4a8e8981983a53fe534c Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 16:19:28 -0400 Subject: [PATCH 21/68] Minor styling fixes in VimeoPublisher and VimeoUploader --- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 5 ++++- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 75551804..e438a934 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -25,6 +25,7 @@ private void Start() { this.hideFlags = HideFlags.HideInInspector; } + public void Init(VimeoRecorder _recorder) { recorder = _recorder; @@ -41,6 +42,7 @@ public void Init(VimeoRecorder _recorder) vimeoUploader.OnError += ApiError; } } + private void RequestComplete(string response) { string video_uri = VimeoUploader.GetVideoPermlink(response); @@ -133,7 +135,8 @@ private void ApiError(string response) if (OnNetworkError != null) { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } - } else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") { + } + else if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.view\"") { if (OnNetworkError != null) { OnNetworkError("You must upgrade your Vimeo account in order to access this privacy feature. https://vimeo.com/upgrade"); } diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 0ce7eb45..2ee80f9f 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -46,7 +46,6 @@ private void RequestComplete(string response) vimeo_url = GetVideoPermlink(response); CreateChunks(file, fileInfo, tusUploadLink); - VideoChunk firstChunk = myChunks.Dequeue(); firstChunk.Upload(); } From 65b761e8a89d7ffb868112b520bafbc01cc103e8 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 16:37:39 -0400 Subject: [PATCH 22/68] Changing the RequestComplete event to OnUploadInit --- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index e438a934..0ce2b71a 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -25,7 +25,7 @@ private void Start() { this.hideFlags = HideFlags.HideInInspector; } - + public void Init(VimeoRecorder _recorder) { recorder = _recorder; @@ -38,12 +38,12 @@ public void Init(VimeoRecorder _recorder) vimeoUploader.OnUploadProgress += UploadProgress; vimeoUploader.OnUploadComplete += UploadComplete; vimeoUploader.OnNetworkError += NetworkError; - vimeoUploader.OnRequestComplete += RequestComplete; + vimeoUploader.OnRequestComplete += OnUploadInit; vimeoUploader.OnError += ApiError; } } - private void RequestComplete(string response) + private void OnUploadInit(string response) { string video_uri = VimeoUploader.GetVideoPermlink(response); video = new VimeoVideo("", video_uri); From b3d586be8e9a71b92ec86839a28593b452c0bd6a Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 17:38:47 -0400 Subject: [PATCH 23/68] Adding getters and unit testing for all variables in VideoChunk.cs --- Assets/Tests/Unit/VideoChunkTest.cs | 61 ++++++++++++++++++++++++ Assets/Tests/Unit/VideoChunkTest.cs.meta | 11 +++++ Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 56 +++++++++++++++------- 3 files changed, 111 insertions(+), 17 deletions(-) create mode 100644 Assets/Tests/Unit/VideoChunkTest.cs create mode 100644 Assets/Tests/Unit/VideoChunkTest.cs.meta diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs new file mode 100644 index 00000000..cd0dfa85 --- /dev/null +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -0,0 +1,61 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System; +using System.Collections; +using System.Text.RegularExpressions; +using Vimeo; + +public class VideoChunkTest : TestConfig +{ + VideoChunk chunk; + + GameObject chunkObj; + + [SetUp] + public void _Before() + { + chunkObj = new GameObject(); + chunk = chunkObj.AddComponent(); + } + + [Test] + public void Init_Works() + { + chunk.Init(0, "test_tus_url", "test_file_path", 10000); + + Assert.AreEqual("test_file_path", chunk.file_path); + Assert.AreEqual("test_tus_url", chunk.url); + Assert.AreEqual(0, chunk.index_byte); + Assert.AreEqual(10000, chunk.chunk_size); + } + + [Test] + public void Stores_And_Disposes_Bytes() + { + chunk.Init(0, "test_tus_url", "test_file_path", 10000); + chunk.bytes = new byte[chunk.chunk_size]; + chunk.bytes[0] = 5; + + Assert.AreEqual(chunk.bytes.Length, chunk.chunk_size); + + chunk.DisposeBytes(); + + Assert.AreNotEqual(chunk.bytes[0], 5); + } + + [Test] + public void Reads_Bytes_From_File() + { + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1); + chunk.ReadBytes(); + + Assert.IsNotEmpty(chunk.bytes); + } + + [TearDown] + public void _After() + { + + } +} diff --git a/Assets/Tests/Unit/VideoChunkTest.cs.meta b/Assets/Tests/Unit/VideoChunkTest.cs.meta new file mode 100644 index 00000000..574dedd0 --- /dev/null +++ b/Assets/Tests/Unit/VideoChunkTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be4ea3625de094a71bb86f8de3f33efa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index cd76fb66..d90ab515 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -1,42 +1,64 @@ using System.IO; using System; -using System.Collections; using System.Collections.Generic; using System.Text; +using System.Collections; using UnityEngine; using UnityEngine.Networking; namespace Vimeo { - class VideoChunk : MonoBehaviour + public class VideoChunk : MonoBehaviour { - private int indexByte; - private string url; - private byte[] bytes; - private string file_path; - private int chunkSize; + private int m_index_byte; + public int index_byte { + get { + return m_index_byte; + } + } + private string m_url; + public string url { + get { + return m_url; + } + } + public byte[] bytes; + private string m_file_path; + public string file_path { + get { + return m_file_path; + } + } + + private int m_chunk_size; + public int chunk_size { + get { + return m_chunk_size; + } + } public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunkUploadComplete; public event UploadEvent OnChunkUploadError; - public void Init(int _indexByte, string _url, string _file_path, int _chunkSize) + public void Init(int _indexByte, string _m_url, string _file_path, int _chunkSize) { - bytes = new byte[_chunkSize]; - file_path = _file_path; - indexByte = _indexByte; - url = _url; + m_chunk_size = _chunkSize; + m_file_path = _file_path; + m_index_byte = _indexByte; + m_url = _m_url; + bytes = new byte[m_chunk_size]; } - private void ReadBytes() + public void ReadBytes() { using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) { - reader.BaseStream.Seek(indexByte, SeekOrigin.Begin); + reader.BaseStream.Seek(m_index_byte, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } } - private void DisposeBytes() + public void DisposeBytes() { Array.Clear(bytes, 0, bytes.Length); } @@ -44,11 +66,11 @@ private void DisposeBytes() private IEnumerator SendTusRequest() { ReadBytes(); - using (UnityWebRequest uploadRequest = UnityWebRequest.Put(url, bytes)) { + using (UnityWebRequest uploadRequest = UnityWebRequest.Put(m_url, bytes)) { uploadRequest.chunkedTransfer = false; uploadRequest.method = "PATCH"; uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", (indexByte).ToString()); + uploadRequest.SetRequestHeader("Upload-Offset", (m_index_byte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); yield return VimeoApi.SendRequest(uploadRequest); From 36b9857ba1f40bd241f46ce65e5ef0a5d63a654d Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 18:02:39 -0400 Subject: [PATCH 24/68] Setting up the VimeoUploader unit testing and getters for all private variables --- Assets/Tests/Unit/VimeoUploaderTest.cs | 38 ++++++++ Assets/Tests/Unit/VimeoUploaderTest.cs.meta | 11 +++ .../Vimeo/Scripts/Services/VimeoUploader.cs | 89 ++++++++++++------- 3 files changed, 106 insertions(+), 32 deletions(-) create mode 100644 Assets/Tests/Unit/VimeoUploaderTest.cs create mode 100644 Assets/Tests/Unit/VimeoUploaderTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs new file mode 100644 index 00000000..ab2cdc42 --- /dev/null +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -0,0 +1,38 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using Vimeo; + +public class VimeoUploaderTest : TestConfig +{ + GameObject uploaderObj; + + VimeoUploader uploader; + + [SetUp] + public void _Before() + { + uploaderObj = new GameObject(); + uploader = uploaderObj.AddComponent(); + } + + [Test] + public void Init_Works() + { + uploader.Init(VALID_RECORDING_TOKEN, 10000); + + Assert.AreEqual(uploader.token, VALID_RECORDING_TOKEN); + Assert.AreEqual(uploader.max_chunk_size, 10000); + } + + [TearDown] + public void _After() + { + + } +} diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs.meta b/Assets/Tests/Unit/VimeoUploaderTest.cs.meta new file mode 100644 index 00000000..0fd2ae35 --- /dev/null +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ad70b4734be642d6ace00c7a9ed630c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 2ee80f9f..c84f069c 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -9,7 +9,7 @@ namespace Vimeo { - class VimeoUploader : VimeoApi + public class VimeoUploader : VimeoApi { public delegate void ChunkUploadEvent(VideoChunk chunk, string msg = ""); public event ChunkUploadEvent OnChunckUploadComplete; @@ -18,13 +18,43 @@ class VimeoUploader : VimeoApi public event UploadAction OnUploadProgress; public event RequestAction OnUploadComplete; - private Queue myChunks; - private string file; - private string vimeo_url; - private FileInfo fileInfo; - public int concurentChunks = 4; - public int maxChunkSize; - public int numChunks; + private Queue m_chunks; + public Queue chunks { + get { + return m_chunks; + } + } + private string m_file; + public string file { + get { + return m_file; + } + } + private string m_vimeo_url; + public string vimeo_url { + get { + return m_vimeo_url; + } + } + private FileInfo m_file_info; + public FileInfo file_info { + get { + return m_file_info; + } + } + private int m_concurent_chunks = 4; + private int m_max_chunk_size; + public int max_chunk_size { + get { + return m_max_chunk_size; + } + } + private int m_num_chunks; + public int num_chunks { + get { + return m_num_chunks; + } + } private void Start() { @@ -33,33 +63,28 @@ private void Start() public void Init(string _token, int _maxChunkSize = 20000) { - myChunks = new Queue(); + m_chunks = new Queue(); token = _token; InitApi(); OnRequestComplete += RequestComplete; - maxChunkSize = _maxChunkSize; + m_max_chunk_size = _maxChunkSize; } private void RequestComplete(string response) { string tusUploadLink = VimeoUploader.GetTusUploadLink(response); - vimeo_url = GetVideoPermlink(response); - CreateChunks(file, fileInfo, tusUploadLink); + m_vimeo_url = GetVideoPermlink(response); + CreateChunks(m_file, m_file_info, tusUploadLink); - VideoChunk firstChunk = myChunks.Dequeue(); + VideoChunk firstChunk = m_chunks.Dequeue(); firstChunk.Upload(); } - public void SetChunkSize(int size) - { - maxChunkSize = size; - } - public void Upload(string _file) { - file = _file; - fileInfo = new FileInfo(_file); - StartCoroutine(RequestTusResource("me/videos", fileInfo.Length)); + m_file = _file; + m_file_info = new FileInfo(m_file); + StartCoroutine(RequestTusResource("me/videos", m_file_info.Length)); } private void OnCompleteChunk(VideoChunk chunk, string msg) @@ -86,24 +111,24 @@ private void OnChunkError(VideoChunk chunk, string err) private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) { //Create the chunks - numChunks = (int)Mathf.Ceil((int)fileInfo.Length / maxChunkSize); + m_num_chunks = (int)Mathf.Ceil((int)fileInfo.Length / m_max_chunk_size); - for (int i = 0; i < numChunks; i++) { - int indexByte = maxChunkSize * i; + for (int i = 0; i < m_num_chunks; i++) { + int indexByte = m_max_chunk_size * i; VideoChunk chunk = this.gameObject.AddComponent(); chunk.hideFlags = HideFlags.HideInInspector; //If we are at the last chunk set the max chunk size to the fractional remainder - if (i + 1 == numChunks) { - int remainder = (int)fileInfo.Length - (maxChunkSize * i); + if (i + 1 == m_num_chunks) { + int remainder = (int)fileInfo.Length - (m_max_chunk_size * i); chunk.Init(indexByte, tusUploadLink, filePath, remainder); } else { - chunk.Init(indexByte, tusUploadLink, filePath, maxChunkSize); + chunk.Init(indexByte, tusUploadLink, filePath, m_max_chunk_size); } chunk.OnChunkUploadComplete += OnCompleteChunk; chunk.OnChunkUploadError += OnChunkError; - myChunks.Enqueue(chunk); + m_chunks.Enqueue(chunk); } } @@ -111,10 +136,10 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi private void UploadNextChunk() { //Make sure the queue is not empty - if (myChunks.Count != 0) { - VideoChunk currentChunk = myChunks.Dequeue(); + if (m_chunks.Count != 0) { + VideoChunk currentChunk = m_chunks.Dequeue(); - float progress = ((float)myChunks.Count / (float)numChunks) * -1.0f + 1.0f; + float progress = ((float)m_chunks.Count / (float)m_num_chunks) * -1.0f + 1.0f; if (OnUploadProgress != null) { OnUploadProgress("Uploading", progress); } @@ -124,7 +149,7 @@ private void UploadNextChunk() OnUploadProgress("UploadComplete", 1f); } if (OnUploadComplete != null) { - OnUploadComplete(vimeo_url); + OnUploadComplete(m_vimeo_url); } } } From f8b63e33e9461d8b975c5a78a715c99541fe5348 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 17 Oct 2018 18:04:16 -0400 Subject: [PATCH 25/68] Destorying the gameobjects properly in unit tests --- Assets/Tests/Unit/VideoChunkTest.cs | 2 +- Assets/Tests/Unit/VimeoUploaderTest.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs index cd0dfa85..1c2f53a1 100644 --- a/Assets/Tests/Unit/VideoChunkTest.cs +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -56,6 +56,6 @@ public void Reads_Bytes_From_File() [TearDown] public void _After() { - + UnityEngine.GameObject.DestroyImmediate(chunkObj); } } diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index ab2cdc42..33d7a933 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -33,6 +33,6 @@ public void Init_Works() [TearDown] public void _After() { - + UnityEngine.GameObject.DestroyImmediate(uploaderObj); } } From 6ab74a9de6d26f4323365a41d4d3e9c890e8a081 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 12:57:47 -0400 Subject: [PATCH 26/68] Add new default to test config --- Assets/Vimeo/Scripts/TestConfigSample.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Assets/Vimeo/Scripts/TestConfigSample.cs b/Assets/Vimeo/Scripts/TestConfigSample.cs index 35134547..da10343d 100644 --- a/Assets/Vimeo/Scripts/TestConfigSample.cs +++ b/Assets/Vimeo/Scripts/TestConfigSample.cs @@ -11,4 +11,5 @@ public class TestConfigSample public const string VALID_VIMEO_VIDEO_ID = "1234"; public const string VALID_STREAMING_TOKEN = "xxx"; public const string VALID_RECORDING_TOKEN = "xxx"; + public string TEST_IMAGE_PATH = Application.dataPath + "/Vimeo/Images/vimeo_v_blue.png"; } \ No newline at end of file From ebbf9ddd28ad30889b464fc68821f859a8b774e4 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 12:58:02 -0400 Subject: [PATCH 27/68] Resolve issues with regex matching (and add tests) --- Assets/Tests/Unit/VimeoPlayerTest.cs | 64 ++++++++++++++++++++++ Assets/Vimeo/Scripts/Player/VimeoPlayer.cs | 9 +-- 2 files changed, 69 insertions(+), 4 deletions(-) diff --git a/Assets/Tests/Unit/VimeoPlayerTest.cs b/Assets/Tests/Unit/VimeoPlayerTest.cs index e006ad6a..17848591 100644 --- a/Assets/Tests/Unit/VimeoPlayerTest.cs +++ b/Assets/Tests/Unit/VimeoPlayerTest.cs @@ -122,4 +122,68 @@ public void _After() { UnityEngine.GameObject.DestroyImmediate(playerObj); } + + + //////////////////////////////////////////////////////// + // Regex pattern matching tests + // See https://regexr.com/3prh6 + public class RegexTests : TestConfig + { + GameObject playerObj; + VimeoPlayer player; + + [SetUp] + public void _Before() + { + playerObj = new GameObject(); + player = playerObj.AddComponent(); + player.videoScreen = GameObject.CreatePrimitive(PrimitiveType.Cube); + player.vimeoVideoId = INVALID_VIMEO_VIDEO_ID; + player.SignIn("xxx"); + player.Start(); + } + + [Test] + public void Load_Video_Parses_Video_Id() + { + player.LoadVideo("1234"); + Assert.AreEqual(player.vimeoVideoId, "1234"); + } + + [Test] + public void Load_Video_Parses_Channel_Video() + { + player.LoadVideo("vimeo.com/channels/360vr/3252329"); + Assert.AreEqual(player.vimeoVideoId, "3252329"); + } + + [Test] + public void Load_Video_Parses_Channel_Video_With_Http() + { + player.LoadVideo("https://vimeo.com/channels/staffpicks/249752354"); + Debug.Log(">>> " + player.vimeoVideoId); + Assert.AreEqual(player.vimeoVideoId, "249752354"); + } + + [Test] + public void Load_Video_Parses_Private_Video() + { + player.LoadVideo("vimeo.com/2304923/4434k3k3j3k3"); + Assert.AreEqual(player.vimeoVideoId, "2304923"); + } + + [Test] + public void Load_Video_Fails_If_Bad_Vimeo_Url() + { + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("Invalid Vimeo URL")); + player.LoadVideo("vimeo.com/casey"); + } + + [TearDown] + public void _After() + { + UnityEngine.GameObject.DestroyImmediate(playerObj); + } + } + } diff --git a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs index 090c5049..f31ed849 100644 --- a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs +++ b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs @@ -72,11 +72,12 @@ public override void SignIn(string _token) public void LoadVideo(string vimeo_url) { - if (vimeo_url != null && vimeo_url != "") { + if (!String.IsNullOrEmpty(vimeo_url)) { vimeoVideo = null; - string[] matches = Regex.Split(vimeo_url, "(vimeo.com)?(/channels/[^/]+)?/?([0-9]+)"); // See https://regexr.com/3prh6 - if (matches[3] != null) { - vimeoVideoId = matches[3]; + Match match = Regex.Match(vimeo_url, "(vimeo.com)?(/channels/[^/]+)?/?([0-9]+)"); + + if (match.Success) { + vimeoVideoId = match.Groups[3].Value; LoadVideo(int.Parse(vimeoVideoId)); } else { From 94ac29a53cf8634843cdc4090ae39771d3ba13e9 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 15:44:47 -0400 Subject: [PATCH 28/68] Added more tests to VimeoUploader and VideoChunk --- Assets/Tests/Unit/VideoChunkTest.cs | 14 ++- Assets/Tests/Unit/VimeoPlayerTest.cs | 1 - Assets/Tests/Unit/VimeoUploaderTest.cs | 98 ++++++++++++++++++- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 7 +- .../Vimeo/Scripts/Services/VimeoUploader.cs | 30 +++--- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 1 - 6 files changed, 115 insertions(+), 36 deletions(-) diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs index 1c2f53a1..63429e21 100644 --- a/Assets/Tests/Unit/VideoChunkTest.cs +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -22,25 +22,23 @@ public void _Before() [Test] public void Init_Works() { + Assert.IsNull(chunk.bytes); + chunk.Init(0, "test_tus_url", "test_file_path", 10000); Assert.AreEqual("test_file_path", chunk.file_path); Assert.AreEqual("test_tus_url", chunk.url); Assert.AreEqual(0, chunk.index_byte); - Assert.AreEqual(10000, chunk.chunk_size); + Assert.AreEqual(10000, chunk.chunk_size); + Assert.AreEqual(chunk.bytes.Length, 10000); } [Test] public void Stores_And_Disposes_Bytes() { chunk.Init(0, "test_tus_url", "test_file_path", 10000); - chunk.bytes = new byte[chunk.chunk_size]; chunk.bytes[0] = 5; - - Assert.AreEqual(chunk.bytes.Length, chunk.chunk_size); - chunk.DisposeBytes(); - Assert.AreNotEqual(chunk.bytes[0], 5); } @@ -48,9 +46,9 @@ public void Stores_And_Disposes_Bytes() public void Reads_Bytes_From_File() { chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1); + Assert.AreEqual(chunk.bytes[0], 0); chunk.ReadBytes(); - - Assert.IsNotEmpty(chunk.bytes); + Assert.AreNotEqual(chunk.bytes[0], 0); } [TearDown] diff --git a/Assets/Tests/Unit/VimeoPlayerTest.cs b/Assets/Tests/Unit/VimeoPlayerTest.cs index 17848591..54f0f60a 100644 --- a/Assets/Tests/Unit/VimeoPlayerTest.cs +++ b/Assets/Tests/Unit/VimeoPlayerTest.cs @@ -161,7 +161,6 @@ public void Load_Video_Parses_Channel_Video() public void Load_Video_Parses_Channel_Video_With_Http() { player.LoadVideo("https://vimeo.com/channels/staffpicks/249752354"); - Debug.Log(">>> " + player.vimeoVideoId); Assert.AreEqual(player.vimeoVideoId, "249752354"); } diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 33d7a933..bc7a2e31 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -11,6 +11,8 @@ public class VimeoUploaderTest : TestConfig { GameObject uploaderObj; + FileInfo testFile; + int testFileSize = 2879; // hardcoding the file size of the test file for reference VimeoUploader uploader; @@ -19,17 +21,109 @@ public void _Before() { uploaderObj = new GameObject(); uploader = uploaderObj.AddComponent(); + uploader.Start(); + uploader.Init("xtokenx"); + testFile = new FileInfo(TEST_IMAGE_PATH); + } + + [Test] + public void Hides_From_Inspector() + { + Assert.AreEqual(uploader.hideFlags, HideFlags.HideInInspector); } [Test] public void Init_Works() { - uploader.Init(VALID_RECORDING_TOKEN, 10000); + uploader.Init("xtokenx", 10000); - Assert.AreEqual(uploader.token, VALID_RECORDING_TOKEN); + Assert.IsNotNull(uploader.chunks); + Assert.AreEqual(uploader.token, "xtokenx"); Assert.AreEqual(uploader.max_chunk_size, 10000); } + [Test] + public void Init_Sets_Default_Chunk_Size() + { + Assert.AreEqual(uploader.max_chunk_size, 1024 * 1024 * 128); + } + + [Test] + public void Upload_Sets_File_Info() + { + uploader.Upload(TEST_IMAGE_PATH); + Assert.AreEqual(uploader.file, TEST_IMAGE_PATH); + Assert.IsNotNull(uploader.file_info); + } + + [Test] + public void CreateChunks_Makes_Multiple_Chunks() + { + uploader.Init("xtokenx", 1000); + uploader.CreateChunks("xxx", testFile, "xxx"); + Assert.AreEqual(uploader.chunks.Count, 3); + } + + [Test] + public void CreateChunks_Makes_One_Chunk_For_Small_Files() + { + uploader.Init("xtokenx", 100000000); + uploader.CreateChunks("xxx", testFile, "xxx"); + Assert.AreEqual(uploader.chunks.Count, 1); + Assert.AreEqual(uploader.chunks.Peek().chunk_size, testFileSize); + } + + [Test] + public void CreateChunks_Properly_Sets_Up_Chunk() + { + uploader.CreateChunks("video file path", testFile, "upload url"); + Assert.AreEqual(uploader.chunks.Peek().url, "upload url"); + Assert.AreEqual(uploader.chunks.Peek().file_path, "video file path"); + } + + [Test] + public void CreateChunks_Sets_Size_Of_Each_Chunk() + { + uploader.Init("xtokenx", 1234); + uploader.CreateChunks("xxx", testFile, "xxx"); + Assert.AreEqual(uploader.chunks.Peek().chunk_size, 1234); + } + + [Test] + public void CreateChunks_Last_Chunk_Is_Remainder() + { + uploader.Init("xtokenx", 1000); + uploader.CreateChunks("xxx", testFile, "xxx"); + Assert.AreEqual( + uploader.chunks.ToArray()[uploader.chunks.Count - 1].chunk_size, 879 + ); + } + + [Test] + public void UploadNextChunk_Dequeues() + { + uploader.CreateChunks(testFile.FullName, testFile, "xxx"); + + int length = uploader.chunks.Count; + uploader.UploadNextChunk(); + Assert.AreEqual(uploader.chunks.Count, length - 1); + } + + // TODO setup way to load mock json file + // [Test] + // public void GetTusUploadLink_Works() + // { + // string uploadLink = VimeoUploader.GetTusUploadLink(mockJson); + // Assert.AreEqual(uploadLink, ""); + // } + + // [Test] + // public void GetVideoPermlink_Works() + // { + // string videoPermalink = VimeoUploader.GetVideoPermlink(mockJson); + // Assert.AreEqual(videoPermalink, ""); + // } + [TearDown] public void _After() { diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 2c816826..8beac69d 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -51,17 +51,12 @@ public enum CommentMode public static string API_URL = "https://api.vimeo.com"; private WWWForm form; - private void Start() + public void Start() { this.hideFlags = HideFlags.HideInInspector; form = new WWWForm(); } - protected void InitApi() - { - Start(); - } - public void GetVideoFileUrlByVimeoId(int video_id, string fields = "name,uri,duration,width,height,spatial,play,description") { StartCoroutine("Request", "/videos/" + video_id + "?fields=" + fields); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index c84f069c..30d34814 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -42,7 +42,7 @@ public FileInfo file_info { return m_file_info; } } - private int m_concurent_chunks = 4; + // private int m_concurent_chunks = 4; Not used private int m_max_chunk_size; public int max_chunk_size { get { @@ -56,22 +56,17 @@ public int num_chunks { } } - private void Start() - { - this.hideFlags = HideFlags.HideInInspector; - } - - public void Init(string _token, int _maxChunkSize = 20000) + public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) { m_chunks = new Queue(); token = _token; - InitApi(); - OnRequestComplete += RequestComplete; - m_max_chunk_size = _maxChunkSize; + m_max_chunk_size = _maxChunkByteSize; } private void RequestComplete(string response) { + OnRequestComplete -= RequestComplete; + string tusUploadLink = VimeoUploader.GetTusUploadLink(response); m_vimeo_url = GetVideoPermlink(response); CreateChunks(m_file, m_file_info, tusUploadLink); @@ -84,6 +79,8 @@ public void Upload(string _file) { m_file = _file; m_file_info = new FileInfo(m_file); + + OnRequestComplete += RequestComplete; StartCoroutine(RequestTusResource("me/videos", m_file_info.Length)); } @@ -94,10 +91,8 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) OnChunckUploadComplete(chunk, msg); } - //Destroy the chunk Destroy(chunk); - //And upload the next one UploadNextChunk(); } @@ -108,10 +103,10 @@ private void OnChunkError(VideoChunk chunk, string err) } } - private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) + public void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) { //Create the chunks - m_num_chunks = (int)Mathf.Ceil((int)fileInfo.Length / m_max_chunk_size); + m_num_chunks = (int)Mathf.Ceil((float)fileInfo.Length / (float)m_max_chunk_size); for (int i = 0; i < m_num_chunks; i++) { int indexByte = m_max_chunk_size * i; @@ -119,7 +114,7 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi chunk.hideFlags = HideFlags.HideInInspector; //If we are at the last chunk set the max chunk size to the fractional remainder - if (i + 1 == m_num_chunks) { + if (i == m_num_chunks - 1) { int remainder = (int)fileInfo.Length - (m_max_chunk_size * i); chunk.Init(indexByte, tusUploadLink, filePath, remainder); } else { @@ -129,11 +124,10 @@ private void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLi chunk.OnChunkUploadComplete += OnCompleteChunk; chunk.OnChunkUploadError += OnChunkError; m_chunks.Enqueue(chunk); - } } - private void UploadNextChunk() + public void UploadNextChunk() { //Make sure the queue is not empty if (m_chunks.Count != 0) { @@ -154,7 +148,7 @@ private void UploadNextChunk() } } - private static string GetTusUploadLink(string response) + public static string GetTusUploadLink(string response) { JSONNode rawJSON = JSON.Parse(response); return rawJSON["upload"]["upload_link"].Value; diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index d90ab515..d25f5d78 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -88,6 +88,5 @@ public void Upload() { StartCoroutine(SendTusRequest()); } - } } \ No newline at end of file From c540ad4a568dfde39c81541223c2618833551a49 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 15:56:24 -0400 Subject: [PATCH 29/68] Include particle system so that the Recorder scene works --- Packages/manifest.json | 1 + 1 file changed, 1 insertion(+) diff --git a/Packages/manifest.json b/Packages/manifest.json index 498fc353..176d135b 100644 --- a/Packages/manifest.json +++ b/Packages/manifest.json @@ -11,6 +11,7 @@ "com.unity.modules.imageconversion": "1.0.0", "com.unity.modules.imgui": "1.0.0", "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.particlesystem": "1.0.0", "com.unity.modules.physics": "1.0.0", "com.unity.modules.screencapture": "1.0.0", "com.unity.modules.terrain": "exclude", From 37af7699cb74c3790b8bf5ea4c893c34020da0f9 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 16:01:32 -0400 Subject: [PATCH 30/68] Changing naming convention to m_camelCase for private and camelCase for public --- Assets/Tests/Unit/VideoChunkTest.cs | 6 +-- Assets/Tests/Unit/VimeoUploaderTest.cs | 14 +++--- .../Vimeo/Scripts/Services/VimeoUploader.cs | 48 +++++++++---------- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 36 +++++++------- 4 files changed, 52 insertions(+), 52 deletions(-) diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs index 63429e21..4e23b1b8 100644 --- a/Assets/Tests/Unit/VideoChunkTest.cs +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -26,10 +26,10 @@ public void Init_Works() chunk.Init(0, "test_tus_url", "test_file_path", 10000); - Assert.AreEqual("test_file_path", chunk.file_path); + Assert.AreEqual("test_file_path", chunk.filePath); Assert.AreEqual("test_tus_url", chunk.url); - Assert.AreEqual(0, chunk.index_byte); - Assert.AreEqual(10000, chunk.chunk_size); + Assert.AreEqual(0, chunk.indexByte); + Assert.AreEqual(10000, chunk.chunkSize); Assert.AreEqual(chunk.bytes.Length, 10000); } diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index bc7a2e31..279e3492 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -39,13 +39,13 @@ public void Init_Works() Assert.IsNotNull(uploader.chunks); Assert.AreEqual(uploader.token, "xtokenx"); - Assert.AreEqual(uploader.max_chunk_size, 10000); + Assert.AreEqual(uploader.maxChunkSize, 10000); } [Test] public void Init_Sets_Default_Chunk_Size() { - Assert.AreEqual(uploader.max_chunk_size, 1024 * 1024 * 128); + Assert.AreEqual(uploader.maxChunkSize, 1024 * 1024 * 128); } [Test] @@ -53,7 +53,7 @@ public void Upload_Sets_File_Info() { uploader.Upload(TEST_IMAGE_PATH); Assert.AreEqual(uploader.file, TEST_IMAGE_PATH); - Assert.IsNotNull(uploader.file_info); + Assert.IsNotNull(uploader.fileInfo); } [Test] @@ -70,7 +70,7 @@ public void CreateChunks_Makes_One_Chunk_For_Small_Files() uploader.Init("xtokenx", 100000000); uploader.CreateChunks("xxx", testFile, "xxx"); Assert.AreEqual(uploader.chunks.Count, 1); - Assert.AreEqual(uploader.chunks.Peek().chunk_size, testFileSize); + Assert.AreEqual(uploader.chunks.Peek().chunkSize, testFileSize); } [Test] @@ -78,7 +78,7 @@ public void CreateChunks_Properly_Sets_Up_Chunk() { uploader.CreateChunks("video file path", testFile, "upload url"); Assert.AreEqual(uploader.chunks.Peek().url, "upload url"); - Assert.AreEqual(uploader.chunks.Peek().file_path, "video file path"); + Assert.AreEqual(uploader.chunks.Peek().filePath, "video file path"); } [Test] @@ -86,7 +86,7 @@ public void CreateChunks_Sets_Size_Of_Each_Chunk() { uploader.Init("xtokenx", 1234); uploader.CreateChunks("xxx", testFile, "xxx"); - Assert.AreEqual(uploader.chunks.Peek().chunk_size, 1234); + Assert.AreEqual(uploader.chunks.Peek().chunkSize, 1234); } [Test] @@ -95,7 +95,7 @@ public void CreateChunks_Last_Chunk_Is_Remainder() uploader.Init("xtokenx", 1000); uploader.CreateChunks("xxx", testFile, "xxx"); Assert.AreEqual( - uploader.chunks.ToArray()[uploader.chunks.Count - 1].chunk_size, 879 + uploader.chunks.ToArray()[uploader.chunks.Count - 1].chunkSize, 879 ); } diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 30d34814..54546b37 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -30,29 +30,29 @@ public string file { return m_file; } } - private string m_vimeo_url; + private string m_vimeoUrl; public string vimeo_url { get { - return m_vimeo_url; + return m_vimeoUrl; } } - private FileInfo m_file_info; - public FileInfo file_info { + private FileInfo m_fileInfo; + public FileInfo fileInfo { get { - return m_file_info; + return m_fileInfo; } } // private int m_concurent_chunks = 4; Not used - private int m_max_chunk_size; - public int max_chunk_size { + private int m_maxChunkSize; + public int maxChunkSize { get { - return m_max_chunk_size; + return m_maxChunkSize; } } - private int m_num_chunks; - public int num_chunks { + private int m_numChunks; + public int numChunks { get { - return m_num_chunks; + return m_numChunks; } } @@ -60,7 +60,7 @@ public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) { m_chunks = new Queue(); token = _token; - m_max_chunk_size = _maxChunkByteSize; + m_maxChunkSize = _maxChunkByteSize; } private void RequestComplete(string response) @@ -68,8 +68,8 @@ private void RequestComplete(string response) OnRequestComplete -= RequestComplete; string tusUploadLink = VimeoUploader.GetTusUploadLink(response); - m_vimeo_url = GetVideoPermlink(response); - CreateChunks(m_file, m_file_info, tusUploadLink); + m_vimeoUrl = GetVideoPermlink(response); + CreateChunks(m_file, m_fileInfo, tusUploadLink); VideoChunk firstChunk = m_chunks.Dequeue(); firstChunk.Upload(); @@ -78,10 +78,10 @@ private void RequestComplete(string response) public void Upload(string _file) { m_file = _file; - m_file_info = new FileInfo(m_file); + m_fileInfo = new FileInfo(m_file); OnRequestComplete += RequestComplete; - StartCoroutine(RequestTusResource("me/videos", m_file_info.Length)); + StartCoroutine(RequestTusResource("me/videos", m_fileInfo.Length)); } private void OnCompleteChunk(VideoChunk chunk, string msg) @@ -106,19 +106,19 @@ private void OnChunkError(VideoChunk chunk, string err) public void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) { //Create the chunks - m_num_chunks = (int)Mathf.Ceil((float)fileInfo.Length / (float)m_max_chunk_size); + m_numChunks = (int)Mathf.Ceil((float)fileInfo.Length / (float)m_maxChunkSize); - for (int i = 0; i < m_num_chunks; i++) { - int indexByte = m_max_chunk_size * i; + for (int i = 0; i < m_numChunks; i++) { + int indexByte = m_maxChunkSize * i; VideoChunk chunk = this.gameObject.AddComponent(); chunk.hideFlags = HideFlags.HideInInspector; //If we are at the last chunk set the max chunk size to the fractional remainder - if (i == m_num_chunks - 1) { - int remainder = (int)fileInfo.Length - (m_max_chunk_size * i); + if (i == m_numChunks - 1) { + int remainder = (int)fileInfo.Length - (m_maxChunkSize * i); chunk.Init(indexByte, tusUploadLink, filePath, remainder); } else { - chunk.Init(indexByte, tusUploadLink, filePath, m_max_chunk_size); + chunk.Init(indexByte, tusUploadLink, filePath, m_maxChunkSize); } chunk.OnChunkUploadComplete += OnCompleteChunk; @@ -133,7 +133,7 @@ public void UploadNextChunk() if (m_chunks.Count != 0) { VideoChunk currentChunk = m_chunks.Dequeue(); - float progress = ((float)m_chunks.Count / (float)m_num_chunks) * -1.0f + 1.0f; + float progress = ((float)m_chunks.Count / (float)m_numChunks) * -1.0f + 1.0f; if (OnUploadProgress != null) { OnUploadProgress("Uploading", progress); } @@ -143,7 +143,7 @@ public void UploadNextChunk() OnUploadProgress("UploadComplete", 1f); } if (OnUploadComplete != null) { - OnUploadComplete(m_vimeo_url); + OnUploadComplete(m_vimeoUrl); } } } diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index d25f5d78..a073c0c6 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -10,10 +10,10 @@ namespace Vimeo { public class VideoChunk : MonoBehaviour { - private int m_index_byte; - public int index_byte { + private int m_indexByte; + public int indexByte { get { - return m_index_byte; + return m_indexByte; } } private string m_url; @@ -23,17 +23,17 @@ public string url { } } public byte[] bytes; - private string m_file_path; - public string file_path { + private string m_filePath; + public string filePath { get { - return m_file_path; + return m_filePath; } } - private int m_chunk_size; - public int chunk_size { + private int m_chunkSize; + public int chunkSize { get { - return m_chunk_size; + return m_chunkSize; } } @@ -41,19 +41,19 @@ public int chunk_size { public event UploadEvent OnChunkUploadComplete; public event UploadEvent OnChunkUploadError; - public void Init(int _indexByte, string _m_url, string _file_path, int _chunkSize) + public void Init(int _indexByte, string _url, string _filePath, int _chunkSize) { - m_chunk_size = _chunkSize; - m_file_path = _file_path; - m_index_byte = _indexByte; - m_url = _m_url; - bytes = new byte[m_chunk_size]; + m_chunkSize = _chunkSize; + m_filePath = _filePath; + m_indexByte = _indexByte; + m_url = _url; + bytes = new byte[m_chunkSize]; } public void ReadBytes() { - using (BinaryReader reader = new BinaryReader(new FileStream(file_path, FileMode.Open, FileAccess.Read))) { - reader.BaseStream.Seek(m_index_byte, SeekOrigin.Begin); + using (BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))) { + reader.BaseStream.Seek(m_indexByte, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } } @@ -70,7 +70,7 @@ private IEnumerator SendTusRequest() uploadRequest.chunkedTransfer = false; uploadRequest.method = "PATCH"; uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", (m_index_byte).ToString()); + uploadRequest.SetRequestHeader("Upload-Offset", (m_indexByte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); yield return VimeoApi.SendRequest(uploadRequest); From ca18fdaa4067caf6062ad90b5bacb938207f8527 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 16:07:44 -0400 Subject: [PATCH 31/68] Getting rid of unneeded argument in CreateChunks in VimeoUploader and fixing unit tests accordingly --- Assets/Tests/Unit/VimeoUploaderTest.cs | 14 +++++++------- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 8 ++++---- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 279e3492..3afba8c4 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -60,7 +60,7 @@ public void Upload_Sets_File_Info() public void CreateChunks_Makes_Multiple_Chunks() { uploader.Init("xtokenx", 1000); - uploader.CreateChunks("xxx", testFile, "xxx"); + uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual(uploader.chunks.Count, 3); } @@ -68,7 +68,7 @@ public void CreateChunks_Makes_Multiple_Chunks() public void CreateChunks_Makes_One_Chunk_For_Small_Files() { uploader.Init("xtokenx", 100000000); - uploader.CreateChunks("xxx", testFile, "xxx"); + uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual(uploader.chunks.Count, 1); Assert.AreEqual(uploader.chunks.Peek().chunkSize, testFileSize); } @@ -76,16 +76,16 @@ public void CreateChunks_Makes_One_Chunk_For_Small_Files() [Test] public void CreateChunks_Properly_Sets_Up_Chunk() { - uploader.CreateChunks("video file path", testFile, "upload url"); + uploader.CreateChunks(testFile, "upload url"); Assert.AreEqual(uploader.chunks.Peek().url, "upload url"); - Assert.AreEqual(uploader.chunks.Peek().filePath, "video file path"); + Assert.AreEqual(uploader.chunks.Peek().filePath, TEST_IMAGE_PATH); } [Test] public void CreateChunks_Sets_Size_Of_Each_Chunk() { uploader.Init("xtokenx", 1234); - uploader.CreateChunks("xxx", testFile, "xxx"); + uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual(uploader.chunks.Peek().chunkSize, 1234); } @@ -93,7 +93,7 @@ public void CreateChunks_Sets_Size_Of_Each_Chunk() public void CreateChunks_Last_Chunk_Is_Remainder() { uploader.Init("xtokenx", 1000); - uploader.CreateChunks("xxx", testFile, "xxx"); + uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual( uploader.chunks.ToArray()[uploader.chunks.Count - 1].chunkSize, 879 ); @@ -102,7 +102,7 @@ public void CreateChunks_Last_Chunk_Is_Remainder() [Test] public void UploadNextChunk_Dequeues() { - uploader.CreateChunks(testFile.FullName, testFile, "xxx"); + uploader.CreateChunks(testFile, "xxx"); int length = uploader.chunks.Count; uploader.UploadNextChunk(); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 54546b37..11eb9c4e 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -69,7 +69,7 @@ private void RequestComplete(string response) string tusUploadLink = VimeoUploader.GetTusUploadLink(response); m_vimeoUrl = GetVideoPermlink(response); - CreateChunks(m_file, m_fileInfo, tusUploadLink); + CreateChunks(m_fileInfo, tusUploadLink); VideoChunk firstChunk = m_chunks.Dequeue(); firstChunk.Upload(); @@ -103,7 +103,7 @@ private void OnChunkError(VideoChunk chunk, string err) } } - public void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLink) + public void CreateChunks(FileInfo fileInfo, string tusUploadLink) { //Create the chunks m_numChunks = (int)Mathf.Ceil((float)fileInfo.Length / (float)m_maxChunkSize); @@ -116,9 +116,9 @@ public void CreateChunks(string filePath, FileInfo fileInfo, string tusUploadLin //If we are at the last chunk set the max chunk size to the fractional remainder if (i == m_numChunks - 1) { int remainder = (int)fileInfo.Length - (m_maxChunkSize * i); - chunk.Init(indexByte, tusUploadLink, filePath, remainder); + chunk.Init(indexByte, tusUploadLink, fileInfo.FullName, remainder); } else { - chunk.Init(indexByte, tusUploadLink, filePath, m_maxChunkSize); + chunk.Init(indexByte, tusUploadLink, fileInfo.FullName, m_maxChunkSize); } chunk.OnChunkUploadComplete += OnCompleteChunk; From 7e57f3e4d7484bb48a41971cb72ef8e120b08a6f Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 17:21:03 -0400 Subject: [PATCH 32/68] Removing the tus response event after the video resource was created and adding VimeoPublisher unit testing --- Assets/Tests/Unit/VimeoPublisherTest.cs | 51 +++++++++++++++ Assets/Tests/Unit/VimeoPublisherTest.cs.meta | 11 ++++ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 65 +++++++++++-------- .../Vimeo/Scripts/Services/VimeoUploader.cs | 10 ++- 4 files changed, 107 insertions(+), 30 deletions(-) create mode 100644 Assets/Tests/Unit/VimeoPublisherTest.cs create mode 100644 Assets/Tests/Unit/VimeoPublisherTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoPublisherTest.cs b/Assets/Tests/Unit/VimeoPublisherTest.cs new file mode 100644 index 00000000..b8da7e55 --- /dev/null +++ b/Assets/Tests/Unit/VimeoPublisherTest.cs @@ -0,0 +1,51 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using Vimeo; +using Vimeo.Recorder; + +public class VimeoPublisherTest : TestConfig +{ + GameObject publisherObj; + + VimeoPublisher publisher; + + VimeoRecorder recorder; + + VimeoUploader uploader; + + [SetUp] + public void _Before() + { + publisherObj = new GameObject(); + + recorder = publisherObj.AddComponent(); + publisher = publisherObj.AddComponent(); + publisher.Init(recorder); + } + + [Test] + public void Init_Works() + { + Assert.IsNotNull(publisher.vimeoUploader); + Assert.IsNotNull(publisher.recorder); + } + + [Test] + public void GetVimeoPermalink_Should_Break_Without_VimeoVideo() + { + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("No vimeo video link found, try recording again")); + Assert.IsNull(publisher.GetVimeoPermalink()); + } + + [TearDown] + public void _After() + { + UnityEngine.GameObject.DestroyImmediate(publisherObj); + } +} diff --git a/Assets/Tests/Unit/VimeoPublisherTest.cs.meta b/Assets/Tests/Unit/VimeoPublisherTest.cs.meta new file mode 100644 index 00000000..7c876a4d --- /dev/null +++ b/Assets/Tests/Unit/VimeoPublisherTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55767550091994d1baf61aa486f226a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 0ce2b71a..93390c1d 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -17,7 +17,12 @@ public class VimeoPublisher : MonoBehaviour [HideInInspector] public VimeoRecorder recorder; // recorder contains all the settings - private VimeoUploader vimeoUploader; + private VimeoUploader m_vimeoUploader; + public VimeoUploader vimeoUploader { + get { + return m_vimeoUploader; + } + } private VimeoVideo video; private Coroutine saveCoroutine; @@ -30,61 +35,65 @@ public void Init(VimeoRecorder _recorder) { recorder = _recorder; - if (vimeoUploader == null) { - vimeoUploader = gameObject.AddComponent(); - vimeoUploader.Init(recorder.GetVimeoToken()); + if (m_vimeoUploader == null) { + m_vimeoUploader = gameObject.AddComponent(); + m_vimeoUploader.Init(recorder.GetVimeoToken()); - vimeoUploader.OnPatchComplete += VideoUpdated; - vimeoUploader.OnUploadProgress += UploadProgress; - vimeoUploader.OnUploadComplete += UploadComplete; - vimeoUploader.OnNetworkError += NetworkError; - vimeoUploader.OnRequestComplete += OnUploadInit; - vimeoUploader.OnError += ApiError; + m_vimeoUploader.OnPatchComplete += VideoUpdated; + m_vimeoUploader.OnUploadProgress += UploadProgress; + m_vimeoUploader.OnUploadComplete += UploadComplete; + m_vimeoUploader.OnNetworkError += NetworkError; + m_vimeoUploader.OnRequestComplete += OnUploadInit; + m_vimeoUploader.OnError += ApiError; } } - private void OnUploadInit(string response) + public void OnUploadInit(string response) { - string video_uri = VimeoUploader.GetVideoPermlink(response); + m_vimeoUploader.OnRequestComplete -= OnUploadInit; + + string video_uri = VimeoUploader.GetVideoUri(response); video = new VimeoVideo("", video_uri); #if UNITY_2018_1_OR_NEWER if (recorder.defaultVideoInput == VideoInputType.Camera360) { - vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); + m_vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); } #endif - vimeoUploader.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); + m_vimeoUploader.SetVideoDescription("Recorded and uploaded with the Vimeo Unity SDK: https://github.com/vimeo/vimeo-unity-sdk"); if (recorder.enableDownloads == false) { - vimeoUploader.SetVideoDownload(recorder.enableDownloads); + m_vimeoUploader.SetVideoDownload(recorder.enableDownloads); } - vimeoUploader.SetVideoComments(recorder.commentMode); - vimeoUploader.SetVideoReviewPage(recorder.enableReviewPage); + m_vimeoUploader.SetVideoComments(recorder.commentMode); + m_vimeoUploader.SetVideoReviewPage(recorder.enableReviewPage); SetVideoName(recorder.GetVideoName()); if (recorder.privacyMode == VimeoApi.PrivacyModeDisplay.OnlyPeopleWithAPassword) { - vimeoUploader.SetVideoPassword(recorder.videoPassword); + m_vimeoUploader.SetVideoPassword(recorder.videoPassword); } SetVideoPrivacyMode(recorder.privacyMode); } public string GetVimeoPermalink() { - if (recorder.videoPermalink != null) { + if (recorder.videoPermalink != null && video.id != null) { if (recorder.defaultShareLink == LinkType.ReviewPage) { return recorder.videoReviewPermalink; } else { return recorder.videoPermalink; } + return "https://vimeo.com/" + video.id; } - return "https://vimeo.com/" + video.id; + Debug.LogError("No vimeo video link found, try recording again"); + return null; } public void PublishVideo(string filename) { Debug.Log("[VimeoRecorder] Uploading to Vimeo"); - vimeoUploader.Upload(filename); + m_vimeoUploader.Upload(filename); } void UploadProgress(string status, float progress) @@ -94,7 +103,7 @@ void UploadProgress(string status, float progress) } } - private void UploadComplete(string video_uri) + private void UploadComplete(string video_url) { if (recorder.openInBrowser == true) { OpenVideo(); @@ -102,7 +111,7 @@ private void UploadComplete(string video_uri) if (OnUploadProgress != null) { OnUploadProgress("UploadComplete", 1f); } - Debug.Log("[VimeoPublisher] Published video to " + video_uri); + Debug.Log("[VimeoPublisher] Published video to " + video_url); } private void VideoUpdated(string response) @@ -112,7 +121,7 @@ private void VideoUpdated(string response) recorder.videoReviewPermalink = json["review_link"]; if (recorder.currentFolder != null && recorder.currentFolder.uri != null) { - vimeoUploader.AddVideoToFolder(video, recorder.currentFolder); + m_vimeoUploader.AddVideoToFolder(video, recorder.currentFolder); } } @@ -154,7 +163,7 @@ public void SetVideoName(string title) { if (title != null && title != "") { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } // DRY - vimeoUploader.SetVideoName(title); + m_vimeoUploader.SetVideoName(title); saveCoroutine = StartCoroutine("SaveVideo"); } } @@ -162,7 +171,7 @@ public void SetVideoName(string title) public void SetVideoPrivacyMode(VimeoApi.PrivacyModeDisplay mode) { if (saveCoroutine != null) { StopCoroutine(saveCoroutine); } - vimeoUploader.SetVideoViewPrivacy(mode); + m_vimeoUploader.SetVideoViewPrivacy(mode); saveCoroutine = StartCoroutine("SaveVideo"); } @@ -171,7 +180,7 @@ private IEnumerator SaveVideo() yield return new WaitForSeconds(1f); if (video != null) { - vimeoUploader.SaveVideo(video); + m_vimeoUploader.SaveVideo(video); } } @@ -192,7 +201,7 @@ void OnDestroy() public void Dispose() { - Destroy(vimeoUploader); + Destroy(m_vimeoUploader); } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 11eb9c4e..74f13834 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -68,7 +68,7 @@ private void RequestComplete(string response) OnRequestComplete -= RequestComplete; string tusUploadLink = VimeoUploader.GetTusUploadLink(response); - m_vimeoUrl = GetVideoPermlink(response); + m_vimeoUrl = GetVideoPermalink(response); CreateChunks(m_fileInfo, tusUploadLink); VideoChunk firstChunk = m_chunks.Dequeue(); @@ -154,10 +154,16 @@ public static string GetTusUploadLink(string response) return rawJSON["upload"]["upload_link"].Value; } - public static string GetVideoPermlink(string response) + public static string GetVideoPermalink(string response) { JSONNode rawJSON = JSON.Parse(response); return rawJSON["link"].Value; } + + public static string GetVideoUri(string response) + { + JSONNode rawJSON = JSON.Parse(response); + return rawJSON["uri"].Value; + } } } \ No newline at end of file From 6ab4a893fcb36dfa496897130c59e8860187038d Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 17:36:31 -0400 Subject: [PATCH 33/68] Fixing unreachable code block and and unit test for it --- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 93390c1d..69fe08d4 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -77,12 +77,15 @@ public void OnUploadInit(string response) public string GetVimeoPermalink() { - if (recorder.videoPermalink != null && video.id != null) { + if (recorder.videoPermalink != null) { if (recorder.defaultShareLink == LinkType.ReviewPage) { return recorder.videoReviewPermalink; } else { return recorder.videoPermalink; } + } + + if (video != null && video.id != 0) { return "https://vimeo.com/" + video.id; } From 5e61dd14974edb9ceebc02cf0dcf2f3bdfc28485 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 17:43:55 -0400 Subject: [PATCH 34/68] Testing uploading & adding to folder new test config var --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 46 ++++++++++++++----- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 4 +- Assets/Vimeo/Scripts/TestConfigSample.cs | 2 + 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 8d1f22b5..6991cc3b 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -5,6 +5,7 @@ using System.Text.RegularExpressions; using Vimeo; using Vimeo.Recorder; +using SimpleJSON; public class VimeoRecorderPlayTest : TestConfig { @@ -17,11 +18,9 @@ public class VimeoRecorderPlayTest : TestConfig VimeoRecorder recorder; bool uploaded; + bool finished; bool error; - float timeout = 30; - float elapsed = 0; - [SetUp] public void _Before() { @@ -56,6 +55,7 @@ public void _Before() recorder.videoName = "(Unity " + Application.unityVersion + ")"; uploaded = false; + finished = false; } [UnityTest] @@ -88,24 +88,46 @@ public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() Assert.IsTrue(uploaded); } - private void TimeoutCheck(string msg = "Test timed out") + private void UploadComplete() { - elapsed += .25f; - if (elapsed >= timeout) { - recorder.CancelRecording(); - Assert.Fail(msg); - } + uploaded = true; } - private void UploadComplete() + [UnityTest] + [Timeout(300000)] + public IEnumerator Uploads_Video_And_Adds_Video_To_Project() + { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + + recorder.currentFolder = new VimeoFolder("Unity Tests", TEST_PROJECT_FOLDER); + recorder.videoName = "Folder Test " + recorder.videoName; + recorder.defaultVideoInput = VideoInputType.Camera; + recorder.SignIn(VALID_RECORDING_TOKEN); + recorder.BeginRecording(); + + recorder.OnUploadComplete += FolderCheckUploadComplete; + + yield return new WaitUntil(()=> finished == true); + } + + private void FolderCheckUploadComplete() { - uploaded = true; + VimeoApi api = recorderObj.AddComponent(); + api.token = VALID_RECORDING_TOKEN; + api.OnRequestComplete += GetFoldersComplete; + api.GetVideosInFolder(new VimeoFolder("Unity Tests", TEST_PROJECT_FOLDER)); + } + + private void GetFoldersComplete(string resp) + { + JSONNode json = JSON.Parse(resp); + Assert.AreEqual(recorder.publisher.video.uri, json["data"][0]["uri"].Value); + finished = true; } [TearDown] public void _After() { - uploaded = false; UnityEngine.GameObject.DestroyImmediate(camObj); UnityEngine.GameObject.DestroyImmediate(light); UnityEngine.GameObject.DestroyImmediate(cube); diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 69fe08d4..e8016e21 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -23,7 +23,7 @@ public VimeoUploader vimeoUploader { return m_vimeoUploader; } } - private VimeoVideo video; + public VimeoVideo video; private Coroutine saveCoroutine; private void Start() @@ -140,7 +140,6 @@ private void ApiError(string response) JSONNode json = JSON.Parse(response); if (json["invalid_parameters"] != null) { - for (int i = 0; i < json["invalid_parameters"].Count; i++) { // TODO use .Value if (json["invalid_parameters"][i]["field"].ToString() == "\"privacy.download\"") { @@ -158,7 +157,6 @@ private void ApiError(string response) } } } - } } diff --git a/Assets/Vimeo/Scripts/TestConfigSample.cs b/Assets/Vimeo/Scripts/TestConfigSample.cs index da10343d..e0f5d88e 100644 --- a/Assets/Vimeo/Scripts/TestConfigSample.cs +++ b/Assets/Vimeo/Scripts/TestConfigSample.cs @@ -11,5 +11,7 @@ public class TestConfigSample public const string VALID_VIMEO_VIDEO_ID = "1234"; public const string VALID_STREAMING_TOKEN = "xxx"; public const string VALID_RECORDING_TOKEN = "xxx"; + public const string TEST_PROJECT_FOLDER = "/users/xxx/projects/xxx"; public string TEST_IMAGE_PATH = Application.dataPath + "/Vimeo/Images/vimeo_v_blue.png"; + } \ No newline at end of file From 49a7ce41678695d24d296a4b318946fded299dca Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 17:44:08 -0400 Subject: [PATCH 35/68] DRYing up some reusable logic --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 39 ++++++++++++----------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 8beac69d..22e690e7 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -174,14 +174,18 @@ public IEnumerator Patch(string url) // Reset the form form = new WWWForm(); + // TODO: DRY with ResponseHandler if (request.responseCode != 200) { Debug.LogError(request.downloadHandler.text); - if (OnError != null) OnError(request.downloadHandler.text); + if (OnError != null) { + OnError(request.downloadHandler.text); + } } else if (OnPatchComplete != null) { OnPatchComplete(request.downloadHandler.text); } } } + public IEnumerator RequestTusResource(string api_path, long fileByteCount) { string tusResourceRequestBody = "{ \"upload\": { \"approach\": \"tus\", \"size\": \"" + fileByteCount.ToString() + "\" } }"; @@ -190,19 +194,11 @@ public IEnumerator RequestTusResource(string api_path, long fileByteCount) using (UnityWebRequest request = UnityWebRequest.Put("https://api.vimeo.com/me/videos", tusResourceRequestBody)) { PrepareTusHeaders(request); yield return VimeoApi.SendRequest(request); - - if (request.error != null) { - if (OnError != null) { - OnError(request.downloadHandler.text); - } - } else { - if (OnRequestComplete != null) { - OnRequestComplete(request.downloadHandler.text); - } - } + ResponseHandler(request); } } } + IEnumerator Put(string api_path) { if (token != null) { @@ -210,16 +206,20 @@ IEnumerator Put(string api_path) using (UnityWebRequest request = UnityWebRequest.Put(API_URL + api_path, data)) { PrepareHeaders(request); yield return VimeoApi.SendRequest(request); + ResponseHandler(request); + } + } + } - if (request.error != null) { - Debug.LogError(request.downloadHandler.text); - if (OnError != null) OnError(request.downloadHandler.text); - } else { - if (OnRequestComplete != null) { - OnRequestComplete(request.downloadHandler.text); - } - } + private void ResponseHandler(UnityWebRequest request) + { + if (request.error != null) { + Debug.LogError(request.downloadHandler.text); + if (OnError != null) { + OnError(request.downloadHandler.text); } + } else if (OnRequestComplete != null) { + OnRequestComplete(request.downloadHandler.text); } } @@ -230,6 +230,7 @@ public IEnumerator Request(string api_path) PrepareHeaders(request); yield return VimeoApi.SendRequest(request); + // TODO: DRY with ResponseHandler if (request.responseCode != 200) { if (request.responseCode == 401) { Debug.LogError("[VimeoApi] 401 Unauthorized request."); From b51816c1bdb3ecbb31596f50f141ae043ebd76f0 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 17:51:32 -0400 Subject: [PATCH 36/68] Nicer handling of VimeoPublisher when video doesn't exist on hard drive Added Unit test --- Assets/Tests/Unit/VimeoPublisherTest.cs | 7 +++++++ Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 8 ++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Assets/Tests/Unit/VimeoPublisherTest.cs b/Assets/Tests/Unit/VimeoPublisherTest.cs index b8da7e55..5b24456b 100644 --- a/Assets/Tests/Unit/VimeoPublisherTest.cs +++ b/Assets/Tests/Unit/VimeoPublisherTest.cs @@ -43,6 +43,13 @@ public void GetVimeoPermalink_Should_Break_Without_VimeoVideo() Assert.IsNull(publisher.GetVimeoPermalink()); } + [Test] + public void PublishVideo_Breaks_When_Video_File_Doesnt_Exist() + { + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("File doesn't exist, try recording it again")); + publisher.PublishVideo("xxx"); + } + [TearDown] public void _After() { diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index e8016e21..3ef55eda 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -95,8 +95,12 @@ public string GetVimeoPermalink() public void PublishVideo(string filename) { - Debug.Log("[VimeoRecorder] Uploading to Vimeo"); - m_vimeoUploader.Upload(filename); + if (System.IO.File.Exists(filename)) { + Debug.Log("[VimeoRecorder] Uploading to Vimeo"); + m_vimeoUploader.Upload(filename); + } else { + Debug.LogError("File doesn't exist, try recording it again"); + } } void UploadProgress(string status, float progress) From 072d30b7d6fb0460fb7f99150b2fc3adad842ff9 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Thu, 18 Oct 2018 18:16:29 -0400 Subject: [PATCH 37/68] Fix test on Windows --- Assets/Tests/Unit/VimeoUploaderTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 3afba8c4..bcf4896c 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -78,7 +78,7 @@ public void CreateChunks_Properly_Sets_Up_Chunk() { uploader.CreateChunks(testFile, "upload url"); Assert.AreEqual(uploader.chunks.Peek().url, "upload url"); - Assert.AreEqual(uploader.chunks.Peek().filePath, TEST_IMAGE_PATH); + Assert.AreEqual(uploader.chunks.Peek().filePath, new FileInfo(TEST_IMAGE_PATH).FullName); } [Test] From 4b019e93962297e38e3bd9e999664e49917ee82d Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Thu, 18 Oct 2018 18:19:41 -0400 Subject: [PATCH 38/68] Moving the response handling to VimeoVideo and deleting the functions from VimeoUploader --- Assets/Vimeo/Scripts/Config/VimeoVideo.cs | 20 ++++++++++++++++ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 3 +-- .../Vimeo/Scripts/Services/VimeoUploader.cs | 24 ++++--------------- 3 files changed, 25 insertions(+), 22 deletions(-) diff --git a/Assets/Vimeo/Scripts/Config/VimeoVideo.cs b/Assets/Vimeo/Scripts/Config/VimeoVideo.cs index 5532e64f..e397eac8 100644 --- a/Assets/Vimeo/Scripts/Config/VimeoVideo.cs +++ b/Assets/Vimeo/Scripts/Config/VimeoVideo.cs @@ -13,6 +13,7 @@ public class VimeoVideo : IComparable { public string name; public string uri; + public string tusUploadLink; public int id; public string description; public int duration; @@ -83,6 +84,25 @@ public VimeoVideo(JSONNode video) progressiveFiles.Sort(SortByQuality); } } + + public VimeoVideo(string jsonString) + { + name = "Untitled"; + tusUploadLink = GetTusUploadLink(jsonString); + uri = GetVideoUri(jsonString); + } + + public string GetTusUploadLink(string response) + { + JSONNode rawJSON = JSON.Parse(response); + return rawJSON["upload"]["upload_link"].Value; + } + + public string GetVideoUri(string response) + { + JSONNode rawJSON = JSON.Parse(response); + return rawJSON["uri"].Value; + } public int CompareTo(VimeoVideo other) { diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 3ef55eda..021d873f 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -52,8 +52,7 @@ public void OnUploadInit(string response) { m_vimeoUploader.OnRequestComplete -= OnUploadInit; - string video_uri = VimeoUploader.GetVideoUri(response); - video = new VimeoVideo("", video_uri); + video = new VimeoVideo(response); #if UNITY_2018_1_OR_NEWER if (recorder.defaultVideoInput == VideoInputType.Camera360) { diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 74f13834..5822037c 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -67,8 +67,10 @@ private void RequestComplete(string response) { OnRequestComplete -= RequestComplete; - string tusUploadLink = VimeoUploader.GetTusUploadLink(response); - m_vimeoUrl = GetVideoPermalink(response); + JSONNode rawJSON = JSON.Parse(response); + + string tusUploadLink = rawJSON["link"].Value; + m_vimeoUrl = rawJSON["upload"]["upload_link"].Value; CreateChunks(m_fileInfo, tusUploadLink); VideoChunk firstChunk = m_chunks.Dequeue(); @@ -147,23 +149,5 @@ public void UploadNextChunk() } } } - - public static string GetTusUploadLink(string response) - { - JSONNode rawJSON = JSON.Parse(response); - return rawJSON["upload"]["upload_link"].Value; - } - - public static string GetVideoPermalink(string response) - { - JSONNode rawJSON = JSON.Parse(response); - return rawJSON["link"].Value; - } - - public static string GetVideoUri(string response) - { - JSONNode rawJSON = JSON.Parse(response); - return rawJSON["uri"].Value; - } } } \ No newline at end of file From a1e7eee5013b1b3124ec5e721e315245b142d52b Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 19 Oct 2018 12:08:09 -0400 Subject: [PATCH 39/68] Writing a generic VimeoVideo that supports the legacy style and tus style VimeoVideo class instintiation --- Assets/Vimeo/Scripts/Config/VimeoVideo.cs | 49 +++++++------------ .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 6 +-- .../Vimeo/Scripts/Services/VimeoUploader.cs | 4 +- 3 files changed, 23 insertions(+), 36 deletions(-) diff --git a/Assets/Vimeo/Scripts/Config/VimeoVideo.cs b/Assets/Vimeo/Scripts/Config/VimeoVideo.cs index e397eac8..061f3abc 100644 --- a/Assets/Vimeo/Scripts/Config/VimeoVideo.cs +++ b/Assets/Vimeo/Scripts/Config/VimeoVideo.cs @@ -40,8 +40,13 @@ public VimeoVideo(string _name, string _uri = null) public VimeoVideo(JSONNode video) { - name = video["name"].Value; - uri = video["uri"].Value; + if (video["name"] != null) { + name = video["name"].Value; + } + + if (video["uri"] != null) { + uri = video["uri"].Value; + } if (video["description"] != null) { description = video["description"].Value; @@ -72,37 +77,19 @@ public VimeoVideo(JSONNode video) name = name + " (" + id + ")"; } } - - files = video["play"]; - - // Sort the progressive files quality - progressiveFiles = new List(); - if (files != null) { - for (int i = 0; i < files["progressive"].Count; i++) { - progressiveFiles.Add(files["progressive"][i]); - } - progressiveFiles.Sort(SortByQuality); + if (video["play"] != null) { + files = video["play"]; + + // Sort the progressive files quality + progressiveFiles = new List(); + if (files != null) { + for (int i = 0; i < files["progressive"].Count; i++) { + progressiveFiles.Add(files["progressive"][i]); + } + progressiveFiles.Sort(SortByQuality); + } } } - - public VimeoVideo(string jsonString) - { - name = "Untitled"; - tusUploadLink = GetTusUploadLink(jsonString); - uri = GetVideoUri(jsonString); - } - - public string GetTusUploadLink(string response) - { - JSONNode rawJSON = JSON.Parse(response); - return rawJSON["upload"]["upload_link"].Value; - } - - public string GetVideoUri(string response) - { - JSONNode rawJSON = JSON.Parse(response); - return rawJSON["uri"].Value; - } public int CompareTo(VimeoVideo other) { diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 021d873f..315179bc 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -51,9 +51,9 @@ public void Init(VimeoRecorder _recorder) public void OnUploadInit(string response) { m_vimeoUploader.OnRequestComplete -= OnUploadInit; - - video = new VimeoVideo(response); - + JSONNode jsonResponse = JSON.Parse(response); + video = new VimeoVideo(jsonResponse); + #if UNITY_2018_1_OR_NEWER if (recorder.defaultVideoInput == VideoInputType.Camera360) { m_vimeoUploader.SetVideoSpatialMode("equirectangular", recorder.defaultRenderMode360 == RenderMode360.Stereo ? "top-bottom" : "mono"); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 5822037c..e6e13694 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -69,8 +69,8 @@ private void RequestComplete(string response) JSONNode rawJSON = JSON.Parse(response); - string tusUploadLink = rawJSON["link"].Value; - m_vimeoUrl = rawJSON["upload"]["upload_link"].Value; + string tusUploadLink = rawJSON["upload"]["upload_link"].Value; + m_vimeoUrl = rawJSON["link"].Value; CreateChunks(m_fileInfo, tusUploadLink); VideoChunk firstChunk = m_chunks.Dequeue(); From 59ac6e3ecd806bc264ff604ea75eced67fb80d3a Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 12:12:31 -0400 Subject: [PATCH 40/68] decrease timeout to 30s --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 6991cc3b..decf94ab 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -59,9 +59,11 @@ public void _Before() } [UnityTest] - [Timeout(300000)] + [Timeout(30000)] public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + recorder.videoName = "Screen Test " + recorder.videoName; recorder.defaultVideoInput = VideoInputType.Screen; recorder.SignIn(VALID_RECORDING_TOKEN); @@ -74,9 +76,11 @@ public IEnumerator Can_Record_Video_From_Screen_With_Valid_Token() } [UnityTest] - [Timeout(300000)] + [Timeout(30000)] public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + recorder.videoName = "MainCamera Test " + recorder.videoName; recorder.defaultVideoInput = VideoInputType.Camera; recorder.SignIn(VALID_RECORDING_TOKEN); @@ -94,7 +98,7 @@ private void UploadComplete() } [UnityTest] - [Timeout(300000)] + [Timeout(30000)] public IEnumerator Uploads_Video_And_Adds_Video_To_Project() { UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); From c2f8125d2bf7787191887e779def6784f8aeb7ff Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 12:12:50 -0400 Subject: [PATCH 41/68] DRY up all the response handling --- Assets/Tests/Play/VimeoPlayerPlayTest.cs | 1 - Assets/Vimeo/Scripts/Player/VimeoPlayer.cs | 2 - Assets/Vimeo/Scripts/Services/VimeoApi.cs | 52 +++++++++------------- 3 files changed, 22 insertions(+), 33 deletions(-) diff --git a/Assets/Tests/Play/VimeoPlayerPlayTest.cs b/Assets/Tests/Play/VimeoPlayerPlayTest.cs index eef8714f..e3205a1c 100644 --- a/Assets/Tests/Play/VimeoPlayerPlayTest.cs +++ b/Assets/Tests/Play/VimeoPlayerPlayTest.cs @@ -64,7 +64,6 @@ public IEnumerator Cant_Stream_Video_With_Invalid_Token() player.PlayVideo(VALID_VIMEO_VIDEO_ID); UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("401")); - UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("Something strange occurred")); while (!triggered) { yield return new WaitForSeconds(.25f); diff --git a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs index f31ed849..e2ee313b 100644 --- a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs +++ b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs @@ -367,8 +367,6 @@ private void VideoMetadataLoad(string response) private void ApiError(string response) { - Debug.LogError(response); - if (OnLoadError != null) { OnLoadError(); } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 22e690e7..0e9a9e05 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -173,16 +173,7 @@ public IEnumerator Patch(string url) // Reset the form form = new WWWForm(); - - // TODO: DRY with ResponseHandler - if (request.responseCode != 200) { - Debug.LogError(request.downloadHandler.text); - if (OnError != null) { - OnError(request.downloadHandler.text); - } - } else if (OnPatchComplete != null) { - OnPatchComplete(request.downloadHandler.text); - } + ResponseHandler(request); } } @@ -214,38 +205,39 @@ IEnumerator Put(string api_path) private void ResponseHandler(UnityWebRequest request) { if (request.error != null) { - Debug.LogError(request.downloadHandler.text); - if (OnError != null) { - OnError(request.downloadHandler.text); + if (request.responseCode == 401) { + SendError("401 Unauthorized request. Are you using a valid token?", request.downloadHandler.text); + } + else if (IsNetworkError(request)) { + Debug.LogError("[VimeoApi] Unable to send request. Are you connected to the internet?"); + if (OnNetworkError != null) { + OnNetworkError(request.error); + } + } + else { + SendError(request.url + " - " + request.downloadHandler.text, request.downloadHandler.text); } } else if (OnRequestComplete != null) { OnRequestComplete(request.downloadHandler.text); } } + private void SendError(string msg, string error) + { + Debug.LogError("[VimeoApi] " + msg); + + if (OnError != null) { + OnError(error); + } + } + public IEnumerator Request(string api_path) { if (token != null) { UnityWebRequest request = UnityWebRequest.Get(API_URL + api_path); PrepareHeaders(request); yield return VimeoApi.SendRequest(request); - - // TODO: DRY with ResponseHandler - if (request.responseCode != 200) { - if (request.responseCode == 401) { - Debug.LogError("[VimeoApi] 401 Unauthorized request."); - } - - if (OnNetworkError != null && IsNetworkError(request)) { - OnNetworkError(request.error); - } - - if (OnError != null && !IsNetworkError(request)) { - OnError(request.downloadHandler.text); - } - } else if (OnRequestComplete != null) { - OnRequestComplete(request.downloadHandler.text); - } + ResponseHandler(request); } } From 8cac312ed29e9f641fedc554273531bb268aca0f Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 12:19:06 -0400 Subject: [PATCH 42/68] remove duplicate error log --- Assets/Vimeo/Scripts/Player/VimeoPlayer.cs | 6 ------ Assets/Vimeo/Scripts/Services/VimeoApi.cs | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs index e2ee313b..28a901c3 100644 --- a/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs +++ b/Assets/Vimeo/Scripts/Player/VimeoPlayer.cs @@ -47,7 +47,6 @@ public void Start() api = gameObject.AddComponent(); api.token = GetVimeoToken(); api.OnError += ApiError; - api.OnNetworkError += NetworkError; } SetupVideoController(); @@ -371,10 +370,5 @@ private void ApiError(string response) OnLoadError(); } } - - private void NetworkError(string error_message) - { - Debug.LogError("It seems like you are not connected to the internet or are having connection problems."); - } } } diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index 0e9a9e05..c1bc9998 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -209,7 +209,7 @@ private void ResponseHandler(UnityWebRequest request) SendError("401 Unauthorized request. Are you using a valid token?", request.downloadHandler.text); } else if (IsNetworkError(request)) { - Debug.LogError("[VimeoApi] Unable to send request. Are you connected to the internet?"); + Debug.LogError("[VimeoApi] It seems like you are not connected to the internet or are having connection problems."); if (OnNetworkError != null) { OnNetworkError(request.error); } From c0528fac906ef717169bab1a44de0376635af6b0 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 12:39:17 -0400 Subject: [PATCH 43/68] Removed OnPatchComplete and updated VimeoPublisher --- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index 315179bc..b912ebbc 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -39,7 +39,6 @@ public void Init(VimeoRecorder _recorder) m_vimeoUploader = gameObject.AddComponent(); m_vimeoUploader.Init(recorder.GetVimeoToken()); - m_vimeoUploader.OnPatchComplete += VideoUpdated; m_vimeoUploader.OnUploadProgress += UploadProgress; m_vimeoUploader.OnUploadComplete += UploadComplete; m_vimeoUploader.OnNetworkError += NetworkError; @@ -51,6 +50,8 @@ public void Init(VimeoRecorder _recorder) public void OnUploadInit(string response) { m_vimeoUploader.OnRequestComplete -= OnUploadInit; + m_vimeoUploader.OnRequestComplete += OnVideoUpdated; + JSONNode jsonResponse = JSON.Parse(response); video = new VimeoVideo(jsonResponse); @@ -120,8 +121,10 @@ private void UploadComplete(string video_url) Debug.Log("[VimeoPublisher] Published video to " + video_url); } - private void VideoUpdated(string response) + private void OnVideoUpdated(string response) { + m_vimeoUploader.OnRequestComplete -= OnVideoUpdated; + JSONNode json = JSON.Parse(response); recorder.videoPermalink = json["link"]; recorder.videoReviewPermalink = json["review_link"]; From 2ed7f59fa828799413b322d1860c4e661b8968c2 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 12:39:48 -0400 Subject: [PATCH 44/68] also remove event from VimeoApi --- Assets/Vimeo/Scripts/Services/VimeoApi.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index c1bc9998..b09f4144 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -40,7 +40,6 @@ public enum CommentMode public delegate void RequestAction(string response); public event RequestAction OnRequestComplete; - public event RequestAction OnPatchComplete; public event RequestAction OnError; public event RequestAction OnNetworkError; From a67bc69a7ed8e76223a832278e67d0d76c3e481e Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Fri, 19 Oct 2018 13:34:06 -0400 Subject: [PATCH 45/68] Multiple upload testing (and add support for paging in api) --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 52 ++++++++++++++++++- .../Vimeo/Scripts/Recorder/VimeoPublisher.cs | 5 +- .../Vimeo/Scripts/Recorder/VimeoRecorder.cs | 4 ++ Assets/Vimeo/Scripts/Services/VimeoApi.cs | 8 +-- 4 files changed, 62 insertions(+), 7 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index decf94ab..7cb6f391 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -21,6 +21,8 @@ public class VimeoRecorderPlayTest : TestConfig bool finished; bool error; + string version = "(Unity " + Application.unityVersion + ")"; + [SetUp] public void _Before() { @@ -52,7 +54,7 @@ public void _Before() recorder.openInBrowser = false; System.DateTime dt = System.DateTime.Now; - recorder.videoName = "(Unity " + Application.unityVersion + ")"; + recorder.videoName = version; uploaded = false; finished = false; @@ -129,6 +131,54 @@ private void GetFoldersComplete(string resp) finished = true; } + [UnityTest] + [Timeout(30000)] + public IEnumerator Multiple_Uploads_Work() + { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + recorder.videoName = "Multi Upload Test #1 " + version; + recorder.OnUploadComplete += FirstUploadComplete; + recorder.SignIn(VALID_RECORDING_TOKEN); + recorder.BeginRecording(); + + yield return new WaitUntil(()=> finished == true); + } + + private void FirstUploadComplete() + { + recorder.OnUploadComplete -= FirstUploadComplete; + Debug.Log("[TEST] FirstUploadComplete"); + UnityEngine.GameObject.DestroyImmediate(cube); + + cube = GameObject.CreatePrimitive(PrimitiveType.Capsule); + cube.AddComponent(); + + recorder.videoName = "Multi Upload Test #2 " + version; + recorder.BeginRecording(); + + recorder.OnUploadComplete += SecondUploadComplete; + } + + private void SecondUploadComplete() + { + Debug.Log("[TEST] SecondUploadComplete"); + VimeoApi api = recorderObj.AddComponent(); + api.token = VALID_RECORDING_TOKEN; + api.OnRequestComplete += CheckRecentVideos; + api.GetRecentUserVideos("name", 2); + } + + private void CheckRecentVideos(string resp) + { + Debug.Log("[TEST] CheckRecentVideos " + resp); + JSONNode json = JSON.Parse(resp); + + Assert.AreEqual(json["data"][0]["name"].Value, "Multi Upload Test #2 " + version); + Assert.AreEqual(json["data"][1]["name"].Value, "Multi Upload Test #1 " + version); + + finished = true; + } + [TearDown] public void _After() { diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index b912ebbc..e143a75a 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -118,13 +118,14 @@ private void UploadComplete(string video_url) if (OnUploadProgress != null) { OnUploadProgress("UploadComplete", 1f); } - Debug.Log("[VimeoPublisher] Published video to " + video_url); + + Debug.Log("[VimeoPublisher] Uploaded video to " + video_url); } private void OnVideoUpdated(string response) { m_vimeoUploader.OnRequestComplete -= OnVideoUpdated; - + JSONNode json = JSON.Parse(response); recorder.videoPermalink = json["link"]; recorder.videoReviewPermalink = json["review_link"]; diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index 3d6db478..6de1d430 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -88,8 +88,12 @@ private void UploadProgress(string status, float progress) uploadProgress = progress; if (status == "UploadComplete") { + publisher.OnUploadProgress -= UploadProgress; + publisher.OnNetworkError -= NetworkError; + isUploading = false; encoder.DeleteVideoFile(); + Destroy(publisher); if (OnUploadComplete != null) { OnUploadComplete(); diff --git a/Assets/Vimeo/Scripts/Services/VimeoApi.cs b/Assets/Vimeo/Scripts/Services/VimeoApi.cs index b09f4144..a8d6f181 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoApi.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoApi.cs @@ -74,14 +74,14 @@ public void AddVideoToFolder(VimeoVideo video, VimeoFolder folder) } } - public void GetRecentUserVideos(string fields = "name,uri") + public void GetRecentUserVideos(string fields = "name,uri", int per_page = 100) { - StartCoroutine("Request", "/me/videos?fields=" + fields + "&per_page=100"); + StartCoroutine("Request", "/me/videos?fields=" + fields + "&per_page=" + per_page); } - public void GetVideosInFolder(VimeoFolder folder, string fields = "name,uri") + public void GetVideosInFolder(VimeoFolder folder, string fields = "name,uri", int per_page = 100) { - StartCoroutine("Request", "/me/folders/" + folder.id + "/videos?fields=" + fields + "&per_page=100"); + StartCoroutine("Request", "/me/folders/" + folder.id + "/videos?fields=" + fields + "&per_page=" + per_page); } public void SetVideoViewPrivacy(PrivacyModeDisplay mode) From 2846a06af743005dc9d1e66c0e7a96e893cbe5b5 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Fri, 19 Oct 2018 17:46:45 -0400 Subject: [PATCH 46/68] Adding chunk based upload progress so the progress bar is responsive on single chunk uploads --- .../Vimeo/Scripts/Services/VimeoUploader.cs | 20 ++++++++++--- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index e6e13694..020e19ff 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -55,6 +55,12 @@ public int numChunks { return m_numChunks; } } + private float m_uploadProgress = 0.0f; + public float uploadProgress { + get { + return m_uploadProgress; + } + } public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) { @@ -98,6 +104,15 @@ private void OnCompleteChunk(VideoChunk chunk, string msg) UploadNextChunk(); } + private void OnUploadChunkProgress(VideoChunk chunk, float progress) + { + //Calculate the addition of each chunk to the total file length (in bytes) + m_uploadProgress = (chunks.Count + 1) * ((progress * (float)chunk.chunkSize) / (float)m_fileInfo.Length); + if (OnUploadProgress != null) { + OnUploadProgress("Uploading", m_uploadProgress); + } + } + private void OnChunkError(VideoChunk chunk, string err) { if (OnChunckUploadError != null) { @@ -125,6 +140,7 @@ public void CreateChunks(FileInfo fileInfo, string tusUploadLink) chunk.OnChunkUploadComplete += OnCompleteChunk; chunk.OnChunkUploadError += OnChunkError; + chunk.OnChunkUploadProgress += OnUploadChunkProgress; m_chunks.Enqueue(chunk); } } @@ -135,10 +151,6 @@ public void UploadNextChunk() if (m_chunks.Count != 0) { VideoChunk currentChunk = m_chunks.Dequeue(); - float progress = ((float)m_chunks.Count / (float)m_numChunks) * -1.0f + 1.0f; - if (OnUploadProgress != null) { - OnUploadProgress("Uploading", progress); - } currentChunk.Upload(); } else { if (OnUploadProgress != null) { diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index a073c0c6..5973d156 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -37,9 +37,20 @@ public int chunkSize { } } + private bool m_isUploadingChunk = false; + public bool isUploadingChunk { + get { + return m_isUploadingChunk; + } + } + public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunkUploadComplete; public event UploadEvent OnChunkUploadError; + public delegate void UploadProgressEvent(VideoChunk chunk, float progress = 0.0f); + public event UploadProgressEvent OnChunkUploadProgress; + + private UnityWebRequest chunkUploadRequest; public void Init(int _indexByte, string _url, string _filePath, int _chunkSize) { @@ -72,18 +83,37 @@ private IEnumerator SendTusRequest() uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); uploadRequest.SetRequestHeader("Upload-Offset", (m_indexByte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + chunkUploadRequest = uploadRequest; + m_isUploadingChunk = true; yield return VimeoApi.SendRequest(uploadRequest); if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { + m_isUploadingChunk = false; OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); } else { + m_isUploadingChunk = false; OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); } } DisposeBytes(); } + private void Update() { + + //Make sure that we are uploading this chunk and the request is not null + if (m_isUploadingChunk && chunkUploadRequest != null) { + + //We only emit events if the upload started (i.e > 0) or it hasn't finished yet (i.e < 1) + if (chunkUploadRequest.uploadProgress > 0.0f && + chunkUploadRequest.uploadProgress < 1.0f) { + OnChunkUploadProgress(this, chunkUploadRequest.uploadProgress); + } + + } + + } + public void Upload() { StartCoroutine(SendTusRequest()); From f62acef0188946073ac63b42f3f590eecd45ae19 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 12:04:48 -0400 Subject: [PATCH 47/68] Add optional argument to the VimeoPublisher for easier testing of different chunk sizes --- Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs index e143a75a..a92c0e97 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoPublisher.cs @@ -31,13 +31,13 @@ private void Start() this.hideFlags = HideFlags.HideInInspector; } - public void Init(VimeoRecorder _recorder) + public void Init(VimeoRecorder _recorder, int _chunkSize = 1024 * 1024 * 128) { recorder = _recorder; if (m_vimeoUploader == null) { m_vimeoUploader = gameObject.AddComponent(); - m_vimeoUploader.Init(recorder.GetVimeoToken()); + m_vimeoUploader.Init(recorder.GetVimeoToken(), _chunkSize); m_vimeoUploader.OnUploadProgress += UploadProgress; m_vimeoUploader.OnUploadComplete += UploadComplete; From 7971c3f42f15ca4b0dbae44d10a5ce72dce3cd03 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 15:55:43 -0400 Subject: [PATCH 48/68] Changing the `VimeoUploader` Queue to a List so it stores all the chunks even after upload --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 20 ++++- Assets/Tests/Unit/VimeoUploaderTest.cs | 24 +++--- .../Vimeo/Scripts/Recorder/VimeoRecorder.cs | 8 +- .../Vimeo/Scripts/Services/VimeoUploader.cs | 81 ++++++++++++++----- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 15 ---- 5 files changed, 97 insertions(+), 51 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 7cb6f391..9759c9e9 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -92,7 +92,25 @@ public IEnumerator Can_Record_Video_From_MainCamera_With_Valid_Token() yield return new WaitUntil(()=> uploaded == true); Assert.IsTrue(uploaded); - } + } + + [UnityTest] + [Timeout(100000)] + public IEnumerator Can_Record_And_Upload_Multiple_Chunks() + { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + + recorder.videoName = "MainCamera Test " + recorder.videoName; + recorder.defaultVideoInput = VideoInputType.Camera; + recorder.customByteChunkSize = 50000; + recorder.SignIn(VALID_RECORDING_TOKEN); + recorder.BeginRecording(); + + recorder.OnUploadComplete += UploadComplete; + + yield return new WaitUntil(()=> uploaded == true); + Assert.IsTrue(uploaded); + } private void UploadComplete() { diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index bcf4896c..4451bcc3 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -70,15 +70,15 @@ public void CreateChunks_Makes_One_Chunk_For_Small_Files() uploader.Init("xtokenx", 100000000); uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual(uploader.chunks.Count, 1); - Assert.AreEqual(uploader.chunks.Peek().chunkSize, testFileSize); + Assert.AreEqual(uploader.chunks[0].chunkSize, testFileSize); } [Test] public void CreateChunks_Properly_Sets_Up_Chunk() { uploader.CreateChunks(testFile, "upload url"); - Assert.AreEqual(uploader.chunks.Peek().url, "upload url"); - Assert.AreEqual(uploader.chunks.Peek().filePath, new FileInfo(TEST_IMAGE_PATH).FullName); + Assert.AreEqual(uploader.chunks[0].url, "upload url"); + Assert.AreEqual(uploader.chunks[0].filePath, new FileInfo(TEST_IMAGE_PATH).FullName); } [Test] @@ -86,7 +86,7 @@ public void CreateChunks_Sets_Size_Of_Each_Chunk() { uploader.Init("xtokenx", 1234); uploader.CreateChunks(testFile, "xxx"); - Assert.AreEqual(uploader.chunks.Peek().chunkSize, 1234); + Assert.AreEqual(uploader.chunks[0].chunkSize, 1234); } [Test] @@ -99,15 +99,15 @@ public void CreateChunks_Last_Chunk_Is_Remainder() ); } - [Test] - public void UploadNextChunk_Dequeues() - { - uploader.CreateChunks(testFile, "xxx"); + // [Test] + // public void UploadNextChunk_Dequeues() + // { + // uploader.CreateChunks(testFile, "xxx"); - int length = uploader.chunks.Count; - uploader.UploadNextChunk(); - Assert.AreEqual(uploader.chunks.Count, length - 1); - } + // int length = uploader.chunks.Count; + // uploader.UploadNextChunk(); + // Assert.AreEqual(uploader.chunks.Count, length - 1); + // } // TODO setup way to load mock json file // [Test] diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index 6de1d430..ddee14d9 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -18,6 +18,12 @@ public class VimeoRecorder : RecorderSettings public bool isRecording = false; public bool isUploading = false; public float uploadProgress = 0; + private int m_customByteChunkSize = 1024 * 1024 * 128; + public int customByteChunkSize { + set { + m_customByteChunkSize = value; + } + } public void Start() { @@ -74,7 +80,7 @@ public void PublishVideo() if (publisher == null) { publisher = gameObject.AddComponent(); - publisher.Init(this); + publisher.Init(this, m_customByteChunkSize); publisher.OnUploadProgress += UploadProgress; publisher.OnNetworkError += NetworkError; diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 020e19ff..241706df 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -18,8 +18,8 @@ public class VimeoUploader : VimeoApi public event UploadAction OnUploadProgress; public event RequestAction OnUploadComplete; - private Queue m_chunks; - public Queue chunks { + private List m_chunks; + public List chunks { get { return m_chunks; } @@ -61,10 +61,13 @@ public float uploadProgress { return m_uploadProgress; } } + private int currentChunkIndex = 0; + private VideoChunk lastChunk; public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) { - m_chunks = new Queue(); + currentChunkIndex = 0; + m_chunks = new List(); token = _token; m_maxChunkSize = _maxChunkByteSize; } @@ -79,8 +82,19 @@ private void RequestComplete(string response) m_vimeoUrl = rawJSON["link"].Value; CreateChunks(m_fileInfo, tusUploadLink); - VideoChunk firstChunk = m_chunks.Dequeue(); - firstChunk.Upload(); + VideoChunk currentChunk = GetNextChunk(); + currentChunk.Upload(); + } + + private VideoChunk GetNextChunk() + { + if (HasChunksLeftToUpload()) { + VideoChunk currentChunk = m_chunks[currentChunkIndex]; + RegisterChunkEvents(currentChunk); + return currentChunk; + } + + return null; } public void Upload(string _file) @@ -92,30 +106,44 @@ public void Upload(string _file) StartCoroutine(RequestTusResource("me/videos", m_fileInfo.Length)); } - private void OnCompleteChunk(VideoChunk chunk, string msg) + private void OnCompleteChunk(VideoChunk chunk, string latestUploadedByte) { - //Emit the event if (OnChunckUploadComplete != null) { - OnChunckUploadComplete(chunk, msg); + // OnUploadProgress("Uploading", 1f); + OnChunckUploadComplete(chunk, latestUploadedByte); } Destroy(chunk); - UploadNextChunk(); + currentChunkIndex++; + UploadNextChunk(GetNextChunk()); } private void OnUploadChunkProgress(VideoChunk chunk, float progress) { - //Calculate the addition of each chunk to the total file length (in bytes) m_uploadProgress = (chunks.Count + 1) * ((progress * (float)chunk.chunkSize) / (float)m_fileInfo.Length); if (OnUploadProgress != null) { OnUploadProgress("Uploading", m_uploadProgress); } } + private void RegisterChunkEvents(VideoChunk chunk) + { + chunk.OnChunkUploadComplete += OnCompleteChunk; + chunk.OnChunkUploadError += OnChunkError; + chunk.OnChunkUploadProgress += OnUploadChunkProgress; + } + + private void DisposeChunkEvents(VideoChunk chunk) + { + chunk.OnChunkUploadComplete -= OnCompleteChunk; + chunk.OnChunkUploadError -= OnChunkError; + chunk.OnChunkUploadProgress -= OnUploadChunkProgress; + } + private void OnChunkError(VideoChunk chunk, string err) { - if (OnChunckUploadError != null) { + if (OnChunckUploadError != null && chunk != null) { OnChunckUploadError(chunk, err); } } @@ -127,7 +155,7 @@ public void CreateChunks(FileInfo fileInfo, string tusUploadLink) for (int i = 0; i < m_numChunks; i++) { int indexByte = m_maxChunkSize * i; - VideoChunk chunk = this.gameObject.AddComponent(); + VideoChunk chunk = gameObject.AddComponent(); chunk.hideFlags = HideFlags.HideInInspector; //If we are at the last chunk set the max chunk size to the fractional remainder @@ -137,21 +165,22 @@ public void CreateChunks(FileInfo fileInfo, string tusUploadLink) } else { chunk.Init(indexByte, tusUploadLink, fileInfo.FullName, m_maxChunkSize); } - - chunk.OnChunkUploadComplete += OnCompleteChunk; - chunk.OnChunkUploadError += OnChunkError; - chunk.OnChunkUploadProgress += OnUploadChunkProgress; - m_chunks.Enqueue(chunk); + m_chunks.Add(chunk); } } - public void UploadNextChunk() + public void UploadNextChunk(VideoChunk currentChunk) { - //Make sure the queue is not empty - if (m_chunks.Count != 0) { - VideoChunk currentChunk = m_chunks.Dequeue(); - + if (lastChunk != null) { + DisposeChunkEvents(lastChunk); + } + + //Make sure there are still chunks to upload + if (currentChunk != null) { currentChunk.Upload(); + + //Store the reference to latest uploaded chunk to de-register events + lastChunk = currentChunk; } else { if (OnUploadProgress != null) { OnUploadProgress("UploadComplete", 1f); @@ -161,5 +190,13 @@ public void UploadNextChunk() } } } + + private bool HasChunksLeftToUpload() + { + if (currentChunkIndex < m_chunks.Count) { + return true; + } + return false; + } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 5973d156..80c94e41 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -99,21 +99,6 @@ private IEnumerator SendTusRequest() DisposeBytes(); } - private void Update() { - - //Make sure that we are uploading this chunk and the request is not null - if (m_isUploadingChunk && chunkUploadRequest != null) { - - //We only emit events if the upload started (i.e > 0) or it hasn't finished yet (i.e < 1) - if (chunkUploadRequest.uploadProgress > 0.0f && - chunkUploadRequest.uploadProgress < 1.0f) { - OnChunkUploadProgress(this, chunkUploadRequest.uploadProgress); - } - - } - - } - public void Upload() { StartCoroutine(SendTusRequest()); From 93bb99aa3f057bad87c7f3fa0995c4c0b274a4eb Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 17:45:07 -0400 Subject: [PATCH 49/68] Implementing the onProgress in the VimeoUploader and DRY'ing VideoChunk --- .../Vimeo/Scripts/Services/VimeoUploader.cs | 109 ++++++++++-------- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 28 ++++- 2 files changed, 86 insertions(+), 51 deletions(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 241706df..cfbb76c4 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -42,6 +42,7 @@ public FileInfo fileInfo { return m_fileInfo; } } + private bool isUploading = false; // private int m_concurent_chunks = 4; Not used private int m_maxChunkSize; public int maxChunkSize { @@ -55,14 +56,10 @@ public int numChunks { return m_numChunks; } } - private float m_uploadProgress = 0.0f; - public float uploadProgress { - get { - return m_uploadProgress; - } - } private int currentChunkIndex = 0; private VideoChunk lastChunk; + public float progressIntervalTime = 0.5f; + private float savedTime = 0.0f; public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) { @@ -72,6 +69,18 @@ public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) m_maxChunkSize = _maxChunkByteSize; } + private void Update() + { + if (isUploading) { + if ((Time.time - savedTime) > progressIntervalTime ) { + OnUploadProgress("Uploading", (float)GetTotalBytesUploaded() / (float)fileInfo.Length); + + savedTime = Time.time; + } + } + + } + private void RequestComplete(string response) { OnRequestComplete -= RequestComplete; @@ -82,21 +91,11 @@ private void RequestComplete(string response) m_vimeoUrl = rawJSON["link"].Value; CreateChunks(m_fileInfo, tusUploadLink); - VideoChunk currentChunk = GetNextChunk(); + VideoChunk currentChunk = m_chunks[currentChunkIndex]; + RegisterChunkEvents(currentChunk); currentChunk.Upload(); } - private VideoChunk GetNextChunk() - { - if (HasChunksLeftToUpload()) { - VideoChunk currentChunk = m_chunks[currentChunkIndex]; - RegisterChunkEvents(currentChunk); - return currentChunk; - } - - return null; - } - public void Upload(string _file) { m_file = _file; @@ -104,41 +103,54 @@ public void Upload(string _file) OnRequestComplete += RequestComplete; StartCoroutine(RequestTusResource("me/videos", m_fileInfo.Length)); + isUploading = true; } private void OnCompleteChunk(VideoChunk chunk, string latestUploadedByte) { if (OnChunckUploadComplete != null) { - // OnUploadProgress("Uploading", 1f); OnChunckUploadComplete(chunk, latestUploadedByte); } - Destroy(chunk); - - currentChunkIndex++; - UploadNextChunk(GetNextChunk()); + if (HasChunksLeftToUpload()){ + UploadNextChunk(); + } else { + isUploading = false; + ClearAllChunks(); + + if (OnUploadProgress != null) { + OnUploadProgress("UploadComplete", 1f); + } + if (OnUploadComplete != null) { + OnUploadComplete(m_vimeoUrl); + } + } } - private void OnUploadChunkProgress(VideoChunk chunk, float progress) + public ulong GetTotalBytesUploaded() { - m_uploadProgress = (chunks.Count + 1) * ((progress * (float)chunk.chunkSize) / (float)m_fileInfo.Length); - if (OnUploadProgress != null) { - OnUploadProgress("Uploading", m_uploadProgress); + ulong sum = 0; + for (int i = 0; i < m_chunks.Count; i++) { + sum += m_chunks[i].GetBytesUploaded(); } + return sum; + } + + public void ClearAllChunks() + { + m_chunks.Clear(); } private void RegisterChunkEvents(VideoChunk chunk) { chunk.OnChunkUploadComplete += OnCompleteChunk; chunk.OnChunkUploadError += OnChunkError; - chunk.OnChunkUploadProgress += OnUploadChunkProgress; } private void DisposeChunkEvents(VideoChunk chunk) { chunk.OnChunkUploadComplete -= OnCompleteChunk; chunk.OnChunkUploadError -= OnChunkError; - chunk.OnChunkUploadProgress -= OnUploadChunkProgress; } private void OnChunkError(VideoChunk chunk, string err) @@ -169,34 +181,37 @@ public void CreateChunks(FileInfo fileInfo, string tusUploadLink) } } - public void UploadNextChunk(VideoChunk currentChunk) + public void UploadNextChunk() { if (lastChunk != null) { DisposeChunkEvents(lastChunk); } - //Make sure there are still chunks to upload - if (currentChunk != null) { - currentChunk.Upload(); - - //Store the reference to latest uploaded chunk to de-register events - lastChunk = currentChunk; - } else { - if (OnUploadProgress != null) { - OnUploadProgress("UploadComplete", 1f); - } - if (OnUploadComplete != null) { - OnUploadComplete(m_vimeoUrl); - } - } + currentChunkIndex++; + + VideoChunk currentChunk = m_chunks[currentChunkIndex]; + RegisterChunkEvents(currentChunk); + + currentChunk.Upload(); + + //Store the reference to latest uploaded chunk to de-register events + lastChunk = currentChunk; } private bool HasChunksLeftToUpload() { - if (currentChunkIndex < m_chunks.Count) { - return true; + return TotalChunksRemaining() > 0; + } + + private int TotalChunksRemaining() + { + int remainingChunks = m_chunks.Count; + for (int i = 0; i < m_chunks.Count; i++) { + if (m_chunks[i].isFinishedUploading) { + remainingChunks--; + } } - return false; + return remainingChunks; } } } \ No newline at end of file diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 80c94e41..5ebcc84a 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -43,14 +43,23 @@ public bool isUploadingChunk { return m_isUploadingChunk; } } + private bool m_isFinishedUploading = false; + public bool isFinishedUploading { + get { + return m_isFinishedUploading; + } + } public delegate void UploadEvent(VideoChunk chunk, string msg = ""); public event UploadEvent OnChunkUploadComplete; public event UploadEvent OnChunkUploadError; - public delegate void UploadProgressEvent(VideoChunk chunk, float progress = 0.0f); - public event UploadProgressEvent OnChunkUploadProgress; - private UnityWebRequest chunkUploadRequest; + private UnityWebRequest m_chunkUploadRequest; + public UnityWebRequest chunkUploadRequest { + get { + return m_chunkUploadRequest; + } + } public void Init(int _indexByte, string _url, string _filePath, int _chunkSize) { @@ -83,7 +92,7 @@ private IEnumerator SendTusRequest() uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); uploadRequest.SetRequestHeader("Upload-Offset", (m_indexByte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); - chunkUploadRequest = uploadRequest; + m_chunkUploadRequest = uploadRequest; m_isUploadingChunk = true; yield return VimeoApi.SendRequest(uploadRequest); @@ -93,12 +102,23 @@ private IEnumerator SendTusRequest() OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); } else { m_isUploadingChunk = false; + m_isFinishedUploading = true; OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); } } DisposeBytes(); } + public ulong GetBytesUploaded() + { + if (m_isUploadingChunk) { + return m_chunkUploadRequest.uploadedBytes; + } else if (m_isFinishedUploading) { + return (ulong)m_chunkSize; + } + return 0; + } + public void Upload() { StartCoroutine(SendTusRequest()); From 7b4ec62044f7f89087ee61fbacd94f13d2ca16ea Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 17:49:37 -0400 Subject: [PATCH 50/68] Changing naming convention in VimeoRecorder --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 2 +- Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 9759c9e9..0f9c1487 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -102,7 +102,7 @@ public IEnumerator Can_Record_And_Upload_Multiple_Chunks() recorder.videoName = "MainCamera Test " + recorder.videoName; recorder.defaultVideoInput = VideoInputType.Camera; - recorder.customByteChunkSize = 50000; + recorder.byteChunkSize = 50000; recorder.SignIn(VALID_RECORDING_TOKEN); recorder.BeginRecording(); diff --git a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs index ddee14d9..b4bbe49c 100644 --- a/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs +++ b/Assets/Vimeo/Scripts/Recorder/VimeoRecorder.cs @@ -18,10 +18,10 @@ public class VimeoRecorder : RecorderSettings public bool isRecording = false; public bool isUploading = false; public float uploadProgress = 0; - private int m_customByteChunkSize = 1024 * 1024 * 128; - public int customByteChunkSize { + private int m_byteChunkSize = 1024 * 1024 * 128; + public int byteChunkSize { set { - m_customByteChunkSize = value; + m_byteChunkSize = value; } } @@ -80,7 +80,7 @@ public void PublishVideo() if (publisher == null) { publisher = gameObject.AddComponent(); - publisher.Init(this, m_customByteChunkSize); + publisher.Init(this, m_byteChunkSize); publisher.OnUploadProgress += UploadProgress; publisher.OnNetworkError += NetworkError; From c96d0276039b78908bee8323d74cbce324d10f79 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 18:27:16 -0400 Subject: [PATCH 51/68] Adding a bunch of tests to `VimeoUploader` and `VideoChunk` and handling error better --- Assets/Tests/Unit/VimeoUploaderTest.cs | 63 ++++++++++++++++--- .../Vimeo/Scripts/Services/VimeoUploader.cs | 28 ++++++--- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 13 +++- 3 files changed, 84 insertions(+), 20 deletions(-) diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 4451bcc3..77965556 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -99,15 +99,62 @@ public void CreateChunks_Last_Chunk_Is_Remainder() ); } - // [Test] - // public void UploadNextChunk_Dequeues() - // { - // uploader.CreateChunks(testFile, "xxx"); + [Test] + public void Upload_Sets_Upload_States() + { + Assert.IsFalse(uploader.isUploading); + uploader.Init("xtokenx", 1000); + uploader.CreateChunks(testFile, "xxx"); + uploader.Upload(testFile.FullName); + Assert.IsTrue(uploader.isUploading); + } - // int length = uploader.chunks.Count; - // uploader.UploadNextChunk(); - // Assert.AreEqual(uploader.chunks.Count, length - 1); - // } + [Test] + public void GetTotalBytes_Returns_Zero_Even_If_No_Chunks_Are_Created() + { + uploader.Init("xtokenx", 1000); + Assert.AreEqual(uploader.GetTotalBytesUploaded(), 0); + } + + [Test] + public void ClearAllChunks_Clears_All_Chunks() + { + uploader.Init("xtokenx", 1000); + uploader.CreateChunks(testFile, "xxx"); + Assert.Greater(uploader.chunks.Count, 0); + uploader.ClearAllChunks(); + Assert.AreEqual(uploader.chunks.Count, 0); + } + + [Test] + public void RegisterChunkEvents_Registers_Chunk_Events() + { + uploader.Init("xtokenx", 1000); + uploader.CreateChunks(testFile, "xxx"); + uploader.chunks[0].OnChunkUploadComplete += new VideoChunk.UploadEvent(delegate { + Debug.Log("yay!"); + }); + uploader.chunks[0].OnChunkUploadError += new VideoChunk.UploadEvent(delegate { + Debug.Log("yay!"); + }); + Assert.IsTrue(uploader.chunks[0].areEventsRegistered()); + Assert.IsFalse(uploader.chunks[1].areEventsRegistered()); + } + + [Test] + public void TotalChunksRemaining_Shows_All_Chunks_Before_Upload_Starts() + { + uploader.Init("xtokenx", 1000); + uploader.CreateChunks(testFile, "xxx"); + Assert.AreEqual(uploader.chunks.Count, uploader.TotalChunksRemaining()); + } + + [Test] + public void TotalChunksRemaining_Does_Not_Break_Before_Chunks_Are_Created() + { + uploader.Init("xtokenx", 1000); + Assert.AreEqual(uploader.TotalChunksRemaining(), 0); + } // TODO setup way to load mock json file // [Test] diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index cfbb76c4..3b632177 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -42,7 +42,12 @@ public FileInfo fileInfo { return m_fileInfo; } } - private bool isUploading = false; + private bool m_isUploading = false; + public bool isUploading { + get { + return m_isUploading; + } + } // private int m_concurent_chunks = 4; Not used private int m_maxChunkSize; public int maxChunkSize { @@ -71,7 +76,7 @@ public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) private void Update() { - if (isUploading) { + if (m_isUploading) { if ((Time.time - savedTime) > progressIntervalTime ) { OnUploadProgress("Uploading", (float)GetTotalBytesUploaded() / (float)fileInfo.Length); @@ -103,7 +108,7 @@ public void Upload(string _file) OnRequestComplete += RequestComplete; StartCoroutine(RequestTusResource("me/videos", m_fileInfo.Length)); - isUploading = true; + m_isUploading = true; } private void OnCompleteChunk(VideoChunk chunk, string latestUploadedByte) @@ -115,7 +120,7 @@ private void OnCompleteChunk(VideoChunk chunk, string latestUploadedByte) if (HasChunksLeftToUpload()){ UploadNextChunk(); } else { - isUploading = false; + m_isUploading = false; ClearAllChunks(); if (OnUploadProgress != null) { @@ -130,8 +135,10 @@ private void OnCompleteChunk(VideoChunk chunk, string latestUploadedByte) public ulong GetTotalBytesUploaded() { ulong sum = 0; - for (int i = 0; i < m_chunks.Count; i++) { - sum += m_chunks[i].GetBytesUploaded(); + if (m_chunks != null) { + for (int i = 0; i < m_chunks.Count; i++) { + sum += m_chunks[i].GetBytesUploaded(); + } } return sum; } @@ -141,13 +148,13 @@ public void ClearAllChunks() m_chunks.Clear(); } - private void RegisterChunkEvents(VideoChunk chunk) + public void RegisterChunkEvents(VideoChunk chunk) { chunk.OnChunkUploadComplete += OnCompleteChunk; chunk.OnChunkUploadError += OnChunkError; } - private void DisposeChunkEvents(VideoChunk chunk) + public void DisposeChunkEvents(VideoChunk chunk) { chunk.OnChunkUploadComplete -= OnCompleteChunk; chunk.OnChunkUploadError -= OnChunkError; @@ -155,6 +162,7 @@ private void DisposeChunkEvents(VideoChunk chunk) private void OnChunkError(VideoChunk chunk, string err) { + m_isUploading = false; if (OnChunckUploadError != null && chunk != null) { OnChunckUploadError(chunk, err); } @@ -198,12 +206,12 @@ public void UploadNextChunk() lastChunk = currentChunk; } - private bool HasChunksLeftToUpload() + public bool HasChunksLeftToUpload() { return TotalChunksRemaining() > 0; } - private int TotalChunksRemaining() + public int TotalChunksRemaining() { int remainingChunks = m_chunks.Count; for (int i = 0; i < m_chunks.Count; i++) { diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 5ebcc84a..677ab279 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -99,11 +99,15 @@ private IEnumerator SendTusRequest() if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { m_isUploadingChunk = false; - OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); + if (OnChunkUploadError != null) { + OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); + } } else { m_isUploadingChunk = false; m_isFinishedUploading = true; - OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); + if (OnChunkUploadComplete != null) { + OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); + } } } DisposeBytes(); @@ -123,5 +127,10 @@ public void Upload() { StartCoroutine(SendTusRequest()); } + + public bool areEventsRegistered() + { + return OnChunkUploadError != null && OnChunkUploadComplete != null; + } } } \ No newline at end of file From 3af05f4bf5e5a0052f470c8d6e931bb2f79a1937 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Mon, 22 Oct 2018 18:58:51 -0400 Subject: [PATCH 52/68] Adding `VideoChunk` tests --- Assets/Tests/Unit/VideoChunkTest.cs | 25 ++++++++++++++++++++++++ Assets/Tests/Unit/VimeoUploaderTest.cs | 15 -------------- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 25 ++++++++++++------------ 3 files changed, 38 insertions(+), 27 deletions(-) diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs index 4e23b1b8..6550cdd4 100644 --- a/Assets/Tests/Unit/VideoChunkTest.cs +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using System; using System.Collections; +using UnityEngine.Networking; using System.Text.RegularExpressions; using Vimeo; @@ -51,6 +52,30 @@ public void Reads_Bytes_From_File() Assert.AreNotEqual(chunk.bytes[0], 0); } + [Test] + public void GetBytesUploaded_Returns_Zero_Before_Uploading() + { + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1); + Assert.AreEqual(chunk.GetBytesUploaded(), 0); + } + + [Test] + public void GetBytesUploaded_Returns_Total_Chunk_Size_When_Finished_Uploading() + { + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1441); + chunk.isFinishedUploading = true; + Assert.AreEqual(chunk.GetBytesUploaded(), 1441); + } + + [Test] + public void GetBytesUploaded_Returns_Uploaded_Bytes_When_Uploading() + { + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1441); + chunk.isUploading = true; + + Assert.AreEqual(chunk.GetBytesUploaded(), 0); + } + [TearDown] public void _After() { diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 77965556..87ceb9f7 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -126,21 +126,6 @@ public void ClearAllChunks_Clears_All_Chunks() Assert.AreEqual(uploader.chunks.Count, 0); } - [Test] - public void RegisterChunkEvents_Registers_Chunk_Events() - { - uploader.Init("xtokenx", 1000); - uploader.CreateChunks(testFile, "xxx"); - uploader.chunks[0].OnChunkUploadComplete += new VideoChunk.UploadEvent(delegate { - Debug.Log("yay!"); - }); - uploader.chunks[0].OnChunkUploadError += new VideoChunk.UploadEvent(delegate { - Debug.Log("yay!"); - }); - Assert.IsTrue(uploader.chunks[0].areEventsRegistered()); - Assert.IsFalse(uploader.chunks[1].areEventsRegistered()); - } - [Test] public void TotalChunksRemaining_Shows_All_Chunks_Before_Upload_Starts() { diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 677ab279..89a9fd43 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -37,10 +37,13 @@ public int chunkSize { } } - private bool m_isUploadingChunk = false; - public bool isUploadingChunk { + private bool m_isUploading = false; + public bool isUploading { get { - return m_isUploadingChunk; + return m_isUploading; + } + set { + m_isUploading = value; } } private bool m_isFinishedUploading = false; @@ -48,6 +51,9 @@ public bool isFinishedUploading { get { return m_isFinishedUploading; } + set { + m_isFinishedUploading = value; + } } public delegate void UploadEvent(VideoChunk chunk, string msg = ""); @@ -93,17 +99,17 @@ private IEnumerator SendTusRequest() uploadRequest.SetRequestHeader("Upload-Offset", (m_indexByte).ToString()); uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); m_chunkUploadRequest = uploadRequest; - m_isUploadingChunk = true; + m_isUploading = true; yield return VimeoApi.SendRequest(uploadRequest); if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { - m_isUploadingChunk = false; + m_isUploading = false; if (OnChunkUploadError != null) { OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); } } else { - m_isUploadingChunk = false; + m_isUploading = false; m_isFinishedUploading = true; if (OnChunkUploadComplete != null) { OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); @@ -115,7 +121,7 @@ private IEnumerator SendTusRequest() public ulong GetBytesUploaded() { - if (m_isUploadingChunk) { + if (m_isUploading && m_chunkUploadRequest != null) { return m_chunkUploadRequest.uploadedBytes; } else if (m_isFinishedUploading) { return (ulong)m_chunkSize; @@ -127,10 +133,5 @@ public void Upload() { StartCoroutine(SendTusRequest()); } - - public bool areEventsRegistered() - { - return OnChunkUploadError != null && OnChunkUploadComplete != null; - } } } \ No newline at end of file From 253b0682c3d5430cc2e95df9da1110aa6fb4bc66 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 10:48:33 -0400 Subject: [PATCH 53/68] Adding VimeoUploader test for uploading a very big file without recording --- .gitignore | 8 ++- Assets/Tests/Play/VimeoUploaderPlayTest.cs | 69 +++++++++++++++++++ .../Tests/Play/VimeoUploaderPlayTest.cs.meta | 11 +++ Assets/Vimeo/Scripts/TestConfigSample.cs | 1 + 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 Assets/Tests/Play/VimeoUploaderPlayTest.cs create mode 100644 Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta diff --git a/.gitignore b/.gitignore index 22f3c949..47b293cc 100644 --- a/.gitignore +++ b/.gitignore @@ -56,4 +56,10 @@ Depthkit* # Test Suite Assets/Vimeo/Scripts/TestConfig.cs* Assets/*TestScene*.unity* -TestResults*.xml \ No newline at end of file +TestResults*.xml + +# Test Assets +*Heavy_Video_Upload_Test_File.mp4* + +# Misc OS files +.DS_Store \ No newline at end of file diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs b/Assets/Tests/Play/VimeoUploaderPlayTest.cs new file mode 100644 index 00000000..c257da87 --- /dev/null +++ b/Assets/Tests/Play/VimeoUploaderPlayTest.cs @@ -0,0 +1,69 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System.Collections; +using System.Text.RegularExpressions; +using Vimeo; +using Vimeo.Recorder; +using SimpleJSON; + +public class VimeoUploaderPlayTest : TestConfig +{ + VimeoUploader uploader; + + GameObject uploaderObj; + + bool uploaded; + + [SetUp] + public void _Before() + { + // Setup only uploader + uploaderObj = new GameObject(); + uploader = uploaderObj.AddComponent(); + uploader.Init(VALID_RECORDING_TOKEN); + uploaded = false; + } + + [UnityTest] + [Timeout(500000)] + public IEnumerator Can_Upload_Very_Big_File() + { + //Register events + uploader.OnUploadComplete += UploadComplete; + uploader.OnUploadProgress += UploadProgress; + uploader.OnError += UploadError; + uploader.OnNetworkError += UploadError; + + //Set the privacy + uploader.SetVideoViewPrivacy(VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink); + uploader.SetVideoName("Big video file upload test"); + + //Upload the big file + uploader.Upload(VERY_BIG_FILE_PATH); + yield return new WaitUntil(()=> uploaded == true ); + Assert.IsTrue(uploaded); + } + + public void UploadComplete(string status) + { + uploaded = true; + } + + public void UploadProgress(string status, float progress) + { + Debug.Log("[VimeoUploader] Uploading file, progress: " + progress); + } + + public void UploadError(string response) + { + Assert.Fail(response); + } + + [TearDown] + public void _After() + { + UnityEngine.GameObject.DestroyImmediate(uploaderObj); + UnityEngine.GameObject.DestroyImmediate(uploader); + } +} diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta b/Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta new file mode 100644 index 00000000..8232071f --- /dev/null +++ b/Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69d58fd9f286b45349ebb28b6949f0fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/TestConfigSample.cs b/Assets/Vimeo/Scripts/TestConfigSample.cs index e0f5d88e..1a135b66 100644 --- a/Assets/Vimeo/Scripts/TestConfigSample.cs +++ b/Assets/Vimeo/Scripts/TestConfigSample.cs @@ -12,6 +12,7 @@ public class TestConfigSample public const string VALID_STREAMING_TOKEN = "xxx"; public const string VALID_RECORDING_TOKEN = "xxx"; public const string TEST_PROJECT_FOLDER = "/users/xxx/projects/xxx"; + public const string VERY_BIG_FILE_PATH = "path/to/very/big/file.mp4"; public string TEST_IMAGE_PATH = Application.dataPath + "/Vimeo/Images/vimeo_v_blue.png"; } \ No newline at end of file From 1f946de8d5c9ad13642facb4651fb052c5ffe6dc Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 10:51:35 -0400 Subject: [PATCH 54/68] Changing the gitignore so it ignores all videos in the test folder --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 47b293cc..7cab16b9 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ Assets/*TestScene*.unity* TestResults*.xml # Test Assets -*Heavy_Video_Upload_Test_File.mp4* +Assets/Tests/*.mp4* # Misc OS files .DS_Store \ No newline at end of file From a71fc125d767a4687a5f6c06b243702ccbeaccce Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 11:00:20 -0400 Subject: [PATCH 55/68] Fix name to specify the type of test --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 0f9c1487..b0d758d5 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -100,7 +100,7 @@ public IEnumerator Can_Record_And_Upload_Multiple_Chunks() { UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); - recorder.videoName = "MainCamera Test " + recorder.videoName; + recorder.videoName = "Multi Chunk Test " + recorder.videoName; recorder.defaultVideoInput = VideoInputType.Camera; recorder.byteChunkSize = 50000; recorder.SignIn(VALID_RECORDING_TOKEN); From 7b4f825aaad4cbeb5efc97449369751b88868772 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 11:15:34 -0400 Subject: [PATCH 56/68] adjust naming to specify platform and unity version --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 2 +- Assets/Tests/Play/VimeoUploaderPlayTest.cs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index b0d758d5..32469e5f 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -21,7 +21,7 @@ public class VimeoRecorderPlayTest : TestConfig bool finished; bool error; - string version = "(Unity " + Application.unityVersion + ")"; + string version = "(" + Application.platform + " " + Application.unityVersion + ")"; [SetUp] public void _Before() diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs b/Assets/Tests/Play/VimeoUploaderPlayTest.cs index c257da87..36814f4a 100644 --- a/Assets/Tests/Play/VimeoUploaderPlayTest.cs +++ b/Assets/Tests/Play/VimeoUploaderPlayTest.cs @@ -29,6 +29,8 @@ public void _Before() [Timeout(500000)] public IEnumerator Can_Upload_Very_Big_File() { + UnityEngine.TestTools.LogAssert.NoUnexpectedReceived(); + //Register events uploader.OnUploadComplete += UploadComplete; uploader.OnUploadProgress += UploadProgress; @@ -37,7 +39,7 @@ public IEnumerator Can_Upload_Very_Big_File() //Set the privacy uploader.SetVideoViewPrivacy(VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink); - uploader.SetVideoName("Big video file upload test"); + uploader.SetVideoName("Large file test (" + Application.platform + " " + Application.unityVersion + ")"); //Upload the big file uploader.Upload(VERY_BIG_FILE_PATH); From 7d4c4121fb07d91363253659bbf51a7167fdabc8 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 11:57:44 -0400 Subject: [PATCH 57/68] Adding temporary naming / privacy workaround so the VimeoUploader could be tested sepratly for large uploads --- Assets/Tests/Play/VimeoUploaderPlayTest.cs | 14 ++++++++++---- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 5 +++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs b/Assets/Tests/Play/VimeoUploaderPlayTest.cs index 36814f4a..92a61e62 100644 --- a/Assets/Tests/Play/VimeoUploaderPlayTest.cs +++ b/Assets/Tests/Play/VimeoUploaderPlayTest.cs @@ -34,13 +34,10 @@ public IEnumerator Can_Upload_Very_Big_File() //Register events uploader.OnUploadComplete += UploadComplete; uploader.OnUploadProgress += UploadProgress; + uploader.OnUploadInit += UploadInit; uploader.OnError += UploadError; uploader.OnNetworkError += UploadError; - //Set the privacy - uploader.SetVideoViewPrivacy(VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink); - uploader.SetVideoName("Large file test (" + Application.platform + " " + Application.unityVersion + ")"); - //Upload the big file uploader.Upload(VERY_BIG_FILE_PATH); yield return new WaitUntil(()=> uploaded == true ); @@ -52,6 +49,15 @@ public void UploadComplete(string status) uploaded = true; } + public void UploadInit(string response) + { + VimeoVideo video = new VimeoVideo(JSON.Parse(response)); + uploader.SetVideoViewPrivacy(VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink); + uploader.SetVideoName("Large file test (" + Application.platform + " " + Application.unityVersion + ")"); + uploader.SaveVideo(video); + + } + public void UploadProgress(string status, float progress) { Debug.Log("[VimeoUploader] Uploading file, progress: " + progress); diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 3b632177..d389733c 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -17,6 +17,7 @@ public class VimeoUploader : VimeoApi public delegate void UploadAction(string status, float progress); public event UploadAction OnUploadProgress; public event RequestAction OnUploadComplete; + public event RequestAction OnUploadInit; private List m_chunks; public List chunks { @@ -99,6 +100,10 @@ private void RequestComplete(string response) VideoChunk currentChunk = m_chunks[currentChunkIndex]; RegisterChunkEvents(currentChunk); currentChunk.Upload(); + + if (OnUploadInit != null) { + OnUploadInit(response); + } } public void Upload(string _file) From 17a0e9c63fdc32c6fb2aaffa80a53a872e76fff7 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 12:15:30 -0400 Subject: [PATCH 58/68] AVPro Movie Capture test --- Assets/Tests/Play/AVProMovieCaptureTest.cs | 90 +++++++++++++++++++ .../Tests/Play/AVProMovieCaptureTest.cs.meta | 11 +++ .../Vimeo/Scripts/Services/VimeoUploader.cs | 4 +- 3 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 Assets/Tests/Play/AVProMovieCaptureTest.cs create mode 100644 Assets/Tests/Play/AVProMovieCaptureTest.cs.meta diff --git a/Assets/Tests/Play/AVProMovieCaptureTest.cs b/Assets/Tests/Play/AVProMovieCaptureTest.cs new file mode 100644 index 00000000..fee1e5a4 --- /dev/null +++ b/Assets/Tests/Play/AVProMovieCaptureTest.cs @@ -0,0 +1,90 @@ +using UnityEngine; +using UnityEngine.TestTools; +using NUnit.Framework; +using System; +using System.Collections; +using System.Text.RegularExpressions; +using Vimeo; +using Vimeo.Recorder; + +#if VIMEO_AVPRO_CAPTURE_SUPPORT +using RenderHeads.Media.AVProMovieCapture; +#endif + +public class AVProMovieCaptureTest : TestConfig +{ +#if VIMEO_AVPRO_CAPTURE_SUPPORT + + GameObject camObj; + GameObject light; + GameObject recorderObj; + GameObject screenObj; + VimeoRecorder recorder; + + bool uploaded; + + RenderHeads.Media.AVProMovieCapture.CaptureFromScreen movieCapture; + + [SetUp] + public void _Before() + { + // Camera setup + camObj = new GameObject("Camera"); + camObj.AddComponent(); + camObj.transform.Translate(0, 0, -3); + + // Light setup + light = new GameObject("Light"); + Light l = light.AddComponent(); + l.type = LightType.Directional; + + // Recorder Setup + recorderObj = new GameObject("Video Recorder"); + recorder = recorderObj.AddComponent(); + recorder.OnUploadComplete += OnUploadComplete; + recorder.videoName = "AVPro Movie Capture (" + Application.platform + " " + Application.unityVersion + ")"; + recorder.privacyMode = VimeoApi.PrivacyModeDisplay.OnlyPeopleWithPrivateLink; + recorder.encoderType = EncoderType.AVProMovieCapture; + + // AVPro setup + movieCapture = recorderObj.AddComponent(); + movieCapture._stopMode = StopMode.SecondsEncoded; + movieCapture._stopSeconds = 10; + movieCapture._useMediaFoundationH264 = true; + + recorder.avproEncoder = movieCapture; + + // Screen setup + screenObj = GameObject.CreatePrimitive(PrimitiveType.Cylinder); + screenObj.AddComponent(); + + camObj.transform.LookAt(screenObj.transform); + + uploaded = false; + } + + [UnityTest] + [Timeout(30000)] + public IEnumerator Can_Record_And_Upload() + { + recorder.SignIn(VALID_RECORDING_TOKEN); + movieCapture.StartCapture(); + yield return new WaitUntil(()=> uploaded == true); + } + + public void OnUploadComplete() + { + uploaded = true; + Assert.IsTrue(true); + } + + [TearDown] + public void _After() + { + UnityEngine.GameObject.DestroyImmediate(camObj); + UnityEngine.GameObject.DestroyImmediate(light); + UnityEngine.GameObject.DestroyImmediate(screenObj); + UnityEngine.GameObject.DestroyImmediate(recorderObj); + } +#endif +} diff --git a/Assets/Tests/Play/AVProMovieCaptureTest.cs.meta b/Assets/Tests/Play/AVProMovieCaptureTest.cs.meta new file mode 100644 index 00000000..a91caaeb --- /dev/null +++ b/Assets/Tests/Play/AVProMovieCaptureTest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 75a75a6242ff86c49b69134023d76cbd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 3b632177..f0e542c6 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -170,7 +170,7 @@ private void OnChunkError(VideoChunk chunk, string err) public void CreateChunks(FileInfo fileInfo, string tusUploadLink) { - //Create the chunks + //Calculate total number of chunks we are uploading m_numChunks = (int)Mathf.Ceil((float)fileInfo.Length / (float)m_maxChunkSize); for (int i = 0; i < m_numChunks; i++) { @@ -178,7 +178,7 @@ public void CreateChunks(FileInfo fileInfo, string tusUploadLink) VideoChunk chunk = gameObject.AddComponent(); chunk.hideFlags = HideFlags.HideInInspector; - //If we are at the last chunk set the max chunk size to the fractional remainder + //If we are at the last chunk set the size to remaining file size if (i == m_numChunks - 1) { int remainder = (int)fileInfo.Length - (m_maxChunkSize * i); chunk.Init(indexByte, tusUploadLink, fileInfo.FullName, remainder); From 7a0b413476df80241408e87ca304bf7b753baeeb Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 13:10:07 -0400 Subject: [PATCH 59/68] Move version error check into _before --- Assets/Tests/Unit/VimeoRecorderTest.cs | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/Assets/Tests/Unit/VimeoRecorderTest.cs b/Assets/Tests/Unit/VimeoRecorderTest.cs index ebfb6981..00d6bd95 100644 --- a/Assets/Tests/Unit/VimeoRecorderTest.cs +++ b/Assets/Tests/Unit/VimeoRecorderTest.cs @@ -27,21 +27,13 @@ public void _Before() System.DateTime dt = System.DateTime.Now; recorder.videoName = "(Unity " + Application.unityVersion + ")"; - - recorder.Start(); - } -#if !UNITY_2017_3_OR_NEWER - [Test] - public void Throw_Error_If_Old_Unity_Version() - { - UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex(" Recording is only avaialabe in 2017.2 or higher")); - GameObject recorderObj = new GameObject(); - VimeoRecorder r = recorderObj.AddComponent(); - r.Start(); - UnityEngine.GameObject.DestroyImmediate(recorderObj); +#if !UNITY_2017_3_OR_NEWER + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("Recording is only avaialabe in 2017.2 or higher")); +#endif + + recorder.Start(); } -#endif [Test] From 2a30f4ef5e6a371f655767ab37dd56a60b137035 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 13:13:22 -0400 Subject: [PATCH 60/68] check that fileinfo is not null --- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index 3fc7b286..b40019e0 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -77,7 +77,7 @@ public void Init(string _token, int _maxChunkByteSize = 1024 * 1024 * 128) private void Update() { - if (m_isUploading) { + if (m_isUploading && fileInfo != null) { if ((Time.time - savedTime) > progressIntervalTime ) { OnUploadProgress("Uploading", (float)GetTotalBytesUploaded() / (float)fileInfo.Length); From 86ef91eb56b08e38550c3a96fdee024b37093d6b Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 13:55:49 -0400 Subject: [PATCH 61/68] Fixes unhandled onProgress error when calling GetBytesUploaded --- Assets/Vimeo/Scripts/Services/VimeoUploader.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs index b40019e0..354c4e3a 100644 --- a/Assets/Vimeo/Scripts/Services/VimeoUploader.cs +++ b/Assets/Vimeo/Scripts/Services/VimeoUploader.cs @@ -142,7 +142,9 @@ public ulong GetTotalBytesUploaded() ulong sum = 0; if (m_chunks != null) { for (int i = 0; i < m_chunks.Count; i++) { - sum += m_chunks[i].GetBytesUploaded(); + if (m_chunks[i] != null) { + sum += m_chunks[i].GetBytesUploaded(); + } } } return sum; From a932b468d0976b7647eb4f3a7d56a39b64b9d990 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 15:51:40 -0400 Subject: [PATCH 62/68] Moving all the tests into an Editor folder so they don't get included in the build process on older versions of Unity (i.e Unity 2017) --- .gitignore | 2 +- Assets/Editor.meta | 8 ++++++++ Assets/{ => Editor}/Tests.meta | 0 Assets/{ => Editor}/Tests/Play.meta | 0 Assets/{ => Editor}/Tests/Play/AVProMovieCaptureTest.cs | 0 .../{ => Editor}/Tests/Play/AVProMovieCaptureTest.cs.meta | 0 Assets/{ => Editor}/Tests/Play/AVProVideoPlayTest.cs | 0 Assets/{ => Editor}/Tests/Play/AVProVideoPlayTest.cs.meta | 0 Assets/{ => Editor}/Tests/Play/ObjectRotation.cs | 0 Assets/{ => Editor}/Tests/Play/ObjectRotation.cs.meta | 0 Assets/{ => Editor}/Tests/Play/PlayTests.asmdef | 0 Assets/{ => Editor}/Tests/Play/PlayTests.asmdef.meta | 0 Assets/{ => Editor}/Tests/Play/VimeoPlayerPlayTest.cs | 0 .../{ => Editor}/Tests/Play/VimeoPlayerPlayTest.cs.meta | 0 Assets/{ => Editor}/Tests/Play/VimeoRecorderPlayTest.cs | 0 .../{ => Editor}/Tests/Play/VimeoRecorderPlayTest.cs.meta | 0 Assets/{ => Editor}/Tests/Play/VimeoUploaderPlayTest.cs | 0 .../{ => Editor}/Tests/Play/VimeoUploaderPlayTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit.meta | 0 Assets/{ => Editor}/Tests/Unit/UnitTests.asmdef | 0 Assets/{ => Editor}/Tests/Unit/UnitTests.asmdef.meta | 0 Assets/{ => Editor}/Tests/Unit/VideoChunkTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VideoChunkTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoPlayerTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoPlayerTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoPublisherTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoPublisherTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoRecorderTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoRecorderTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoSettingsTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoSettingsTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoUploaderTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoUploaderTest.cs.meta | 0 Assets/{ => Editor}/Tests/Unit/VimeoVideoTest.cs | 0 Assets/{ => Editor}/Tests/Unit/VimeoVideoTest.cs.meta | 0 35 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 Assets/Editor.meta rename Assets/{ => Editor}/Tests.meta (100%) rename Assets/{ => Editor}/Tests/Play.meta (100%) rename Assets/{ => Editor}/Tests/Play/AVProMovieCaptureTest.cs (100%) rename Assets/{ => Editor}/Tests/Play/AVProMovieCaptureTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Play/AVProVideoPlayTest.cs (100%) rename Assets/{ => Editor}/Tests/Play/AVProVideoPlayTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Play/ObjectRotation.cs (100%) rename Assets/{ => Editor}/Tests/Play/ObjectRotation.cs.meta (100%) rename Assets/{ => Editor}/Tests/Play/PlayTests.asmdef (100%) rename Assets/{ => Editor}/Tests/Play/PlayTests.asmdef.meta (100%) rename Assets/{ => Editor}/Tests/Play/VimeoPlayerPlayTest.cs (100%) rename Assets/{ => Editor}/Tests/Play/VimeoPlayerPlayTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Play/VimeoRecorderPlayTest.cs (100%) rename Assets/{ => Editor}/Tests/Play/VimeoRecorderPlayTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Play/VimeoUploaderPlayTest.cs (100%) rename Assets/{ => Editor}/Tests/Play/VimeoUploaderPlayTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit.meta (100%) rename Assets/{ => Editor}/Tests/Unit/UnitTests.asmdef (100%) rename Assets/{ => Editor}/Tests/Unit/UnitTests.asmdef.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VideoChunkTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VideoChunkTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoPlayerTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoPlayerTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoPublisherTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoPublisherTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoRecorderTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoRecorderTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoSettingsTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoSettingsTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoUploaderTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoUploaderTest.cs.meta (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoVideoTest.cs (100%) rename Assets/{ => Editor}/Tests/Unit/VimeoVideoTest.cs.meta (100%) diff --git a/.gitignore b/.gitignore index 7cab16b9..3c7318ef 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ Assets/*TestScene*.unity* TestResults*.xml # Test Assets -Assets/Tests/*.mp4* +Assets/Editor/Tests/*.mp4* # Misc OS files .DS_Store \ No newline at end of file diff --git a/Assets/Editor.meta b/Assets/Editor.meta new file mode 100644 index 00000000..cb8c0c32 --- /dev/null +++ b/Assets/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 63b999de8039248dc9dc5cd34a784a14 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests.meta b/Assets/Editor/Tests.meta similarity index 100% rename from Assets/Tests.meta rename to Assets/Editor/Tests.meta diff --git a/Assets/Tests/Play.meta b/Assets/Editor/Tests/Play.meta similarity index 100% rename from Assets/Tests/Play.meta rename to Assets/Editor/Tests/Play.meta diff --git a/Assets/Tests/Play/AVProMovieCaptureTest.cs b/Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs similarity index 100% rename from Assets/Tests/Play/AVProMovieCaptureTest.cs rename to Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs diff --git a/Assets/Tests/Play/AVProMovieCaptureTest.cs.meta b/Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs.meta similarity index 100% rename from Assets/Tests/Play/AVProMovieCaptureTest.cs.meta rename to Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs.meta diff --git a/Assets/Tests/Play/AVProVideoPlayTest.cs b/Assets/Editor/Tests/Play/AVProVideoPlayTest.cs similarity index 100% rename from Assets/Tests/Play/AVProVideoPlayTest.cs rename to Assets/Editor/Tests/Play/AVProVideoPlayTest.cs diff --git a/Assets/Tests/Play/AVProVideoPlayTest.cs.meta b/Assets/Editor/Tests/Play/AVProVideoPlayTest.cs.meta similarity index 100% rename from Assets/Tests/Play/AVProVideoPlayTest.cs.meta rename to Assets/Editor/Tests/Play/AVProVideoPlayTest.cs.meta diff --git a/Assets/Tests/Play/ObjectRotation.cs b/Assets/Editor/Tests/Play/ObjectRotation.cs similarity index 100% rename from Assets/Tests/Play/ObjectRotation.cs rename to Assets/Editor/Tests/Play/ObjectRotation.cs diff --git a/Assets/Tests/Play/ObjectRotation.cs.meta b/Assets/Editor/Tests/Play/ObjectRotation.cs.meta similarity index 100% rename from Assets/Tests/Play/ObjectRotation.cs.meta rename to Assets/Editor/Tests/Play/ObjectRotation.cs.meta diff --git a/Assets/Tests/Play/PlayTests.asmdef b/Assets/Editor/Tests/Play/PlayTests.asmdef similarity index 100% rename from Assets/Tests/Play/PlayTests.asmdef rename to Assets/Editor/Tests/Play/PlayTests.asmdef diff --git a/Assets/Tests/Play/PlayTests.asmdef.meta b/Assets/Editor/Tests/Play/PlayTests.asmdef.meta similarity index 100% rename from Assets/Tests/Play/PlayTests.asmdef.meta rename to Assets/Editor/Tests/Play/PlayTests.asmdef.meta diff --git a/Assets/Tests/Play/VimeoPlayerPlayTest.cs b/Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs similarity index 100% rename from Assets/Tests/Play/VimeoPlayerPlayTest.cs rename to Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs diff --git a/Assets/Tests/Play/VimeoPlayerPlayTest.cs.meta b/Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs.meta similarity index 100% rename from Assets/Tests/Play/VimeoPlayerPlayTest.cs.meta rename to Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs.meta diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs similarity index 100% rename from Assets/Tests/Play/VimeoRecorderPlayTest.cs rename to Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs.meta b/Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs.meta similarity index 100% rename from Assets/Tests/Play/VimeoRecorderPlayTest.cs.meta rename to Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs.meta diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs b/Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs similarity index 100% rename from Assets/Tests/Play/VimeoUploaderPlayTest.cs rename to Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs diff --git a/Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta b/Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs.meta similarity index 100% rename from Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta rename to Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs.meta diff --git a/Assets/Tests/Unit.meta b/Assets/Editor/Tests/Unit.meta similarity index 100% rename from Assets/Tests/Unit.meta rename to Assets/Editor/Tests/Unit.meta diff --git a/Assets/Tests/Unit/UnitTests.asmdef b/Assets/Editor/Tests/Unit/UnitTests.asmdef similarity index 100% rename from Assets/Tests/Unit/UnitTests.asmdef rename to Assets/Editor/Tests/Unit/UnitTests.asmdef diff --git a/Assets/Tests/Unit/UnitTests.asmdef.meta b/Assets/Editor/Tests/Unit/UnitTests.asmdef.meta similarity index 100% rename from Assets/Tests/Unit/UnitTests.asmdef.meta rename to Assets/Editor/Tests/Unit/UnitTests.asmdef.meta diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Editor/Tests/Unit/VideoChunkTest.cs similarity index 100% rename from Assets/Tests/Unit/VideoChunkTest.cs rename to Assets/Editor/Tests/Unit/VideoChunkTest.cs diff --git a/Assets/Tests/Unit/VideoChunkTest.cs.meta b/Assets/Editor/Tests/Unit/VideoChunkTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VideoChunkTest.cs.meta rename to Assets/Editor/Tests/Unit/VideoChunkTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoPlayerTest.cs b/Assets/Editor/Tests/Unit/VimeoPlayerTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoPlayerTest.cs rename to Assets/Editor/Tests/Unit/VimeoPlayerTest.cs diff --git a/Assets/Tests/Unit/VimeoPlayerTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoPlayerTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoPlayerTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoPlayerTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoPublisherTest.cs b/Assets/Editor/Tests/Unit/VimeoPublisherTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoPublisherTest.cs rename to Assets/Editor/Tests/Unit/VimeoPublisherTest.cs diff --git a/Assets/Tests/Unit/VimeoPublisherTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoPublisherTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoPublisherTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoPublisherTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoRecorderTest.cs b/Assets/Editor/Tests/Unit/VimeoRecorderTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoRecorderTest.cs rename to Assets/Editor/Tests/Unit/VimeoRecorderTest.cs diff --git a/Assets/Tests/Unit/VimeoRecorderTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoRecorderTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoRecorderTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoRecorderTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoSettingsTest.cs b/Assets/Editor/Tests/Unit/VimeoSettingsTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoSettingsTest.cs rename to Assets/Editor/Tests/Unit/VimeoSettingsTest.cs diff --git a/Assets/Tests/Unit/VimeoSettingsTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoSettingsTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoSettingsTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoSettingsTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Editor/Tests/Unit/VimeoUploaderTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoUploaderTest.cs rename to Assets/Editor/Tests/Unit/VimeoUploaderTest.cs diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoUploaderTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoUploaderTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoUploaderTest.cs.meta diff --git a/Assets/Tests/Unit/VimeoVideoTest.cs b/Assets/Editor/Tests/Unit/VimeoVideoTest.cs similarity index 100% rename from Assets/Tests/Unit/VimeoVideoTest.cs rename to Assets/Editor/Tests/Unit/VimeoVideoTest.cs diff --git a/Assets/Tests/Unit/VimeoVideoTest.cs.meta b/Assets/Editor/Tests/Unit/VimeoVideoTest.cs.meta similarity index 100% rename from Assets/Tests/Unit/VimeoVideoTest.cs.meta rename to Assets/Editor/Tests/Unit/VimeoVideoTest.cs.meta From ee67c7b482092ef83dfd91099f57e70c286c8b5f Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 16:12:18 -0400 Subject: [PATCH 63/68] Move tests back into root folder --- Assets/Editor.meta | 8 ------- Assets/{Editor => }/Tests.meta | 0 .../Heavy_Video_Upload_Test_File.mp4.meta | 22 +++++++++++++++++++ Assets/{Editor => }/Tests/Play.meta | 0 .../Tests/Play/AVProMovieCaptureTest.cs | 0 .../Tests/Play/AVProMovieCaptureTest.cs.meta | 0 .../Tests/Play/AVProVideoPlayTest.cs | 0 .../Tests/Play/AVProVideoPlayTest.cs.meta | 0 .../{Editor => }/Tests/Play/ObjectRotation.cs | 0 .../Tests/Play/ObjectRotation.cs.meta | 0 .../{Editor => }/Tests/Play/PlayTests.asmdef | 0 .../Tests/Play/PlayTests.asmdef.meta | 0 .../Tests/Play/VimeoPlayerPlayTest.cs | 0 .../Tests/Play/VimeoPlayerPlayTest.cs.meta | 0 .../Tests/Play/VimeoRecorderPlayTest.cs | 0 .../Tests/Play/VimeoRecorderPlayTest.cs.meta | 0 .../Tests/Play/VimeoUploaderPlayTest.cs | 0 .../Tests/Play/VimeoUploaderPlayTest.cs.meta | 0 Assets/{Editor => }/Tests/Unit.meta | 0 .../{Editor => }/Tests/Unit/UnitTests.asmdef | 0 .../Tests/Unit/UnitTests.asmdef.meta | 0 .../{Editor => }/Tests/Unit/VideoChunkTest.cs | 0 .../Tests/Unit/VideoChunkTest.cs.meta | 0 .../Tests/Unit/VimeoPlayerTest.cs | 0 .../Tests/Unit/VimeoPlayerTest.cs.meta | 0 .../Tests/Unit/VimeoPublisherTest.cs | 0 .../Tests/Unit/VimeoPublisherTest.cs.meta | 0 .../Tests/Unit/VimeoRecorderTest.cs | 0 .../Tests/Unit/VimeoRecorderTest.cs.meta | 0 .../Tests/Unit/VimeoSettingsTest.cs | 0 .../Tests/Unit/VimeoSettingsTest.cs.meta | 0 .../Tests/Unit/VimeoUploaderTest.cs | 0 .../Tests/Unit/VimeoUploaderTest.cs.meta | 0 .../{Editor => }/Tests/Unit/VimeoVideoTest.cs | 0 .../Tests/Unit/VimeoVideoTest.cs.meta | 0 35 files changed, 22 insertions(+), 8 deletions(-) delete mode 100644 Assets/Editor.meta rename Assets/{Editor => }/Tests.meta (100%) create mode 100644 Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta rename Assets/{Editor => }/Tests/Play.meta (100%) rename Assets/{Editor => }/Tests/Play/AVProMovieCaptureTest.cs (100%) rename Assets/{Editor => }/Tests/Play/AVProMovieCaptureTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Play/AVProVideoPlayTest.cs (100%) rename Assets/{Editor => }/Tests/Play/AVProVideoPlayTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Play/ObjectRotation.cs (100%) rename Assets/{Editor => }/Tests/Play/ObjectRotation.cs.meta (100%) rename Assets/{Editor => }/Tests/Play/PlayTests.asmdef (100%) rename Assets/{Editor => }/Tests/Play/PlayTests.asmdef.meta (100%) rename Assets/{Editor => }/Tests/Play/VimeoPlayerPlayTest.cs (100%) rename Assets/{Editor => }/Tests/Play/VimeoPlayerPlayTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Play/VimeoRecorderPlayTest.cs (100%) rename Assets/{Editor => }/Tests/Play/VimeoRecorderPlayTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Play/VimeoUploaderPlayTest.cs (100%) rename Assets/{Editor => }/Tests/Play/VimeoUploaderPlayTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit.meta (100%) rename Assets/{Editor => }/Tests/Unit/UnitTests.asmdef (100%) rename Assets/{Editor => }/Tests/Unit/UnitTests.asmdef.meta (100%) rename Assets/{Editor => }/Tests/Unit/VideoChunkTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VideoChunkTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoPlayerTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoPlayerTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoPublisherTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoPublisherTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoRecorderTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoRecorderTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoSettingsTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoSettingsTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoUploaderTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoUploaderTest.cs.meta (100%) rename Assets/{Editor => }/Tests/Unit/VimeoVideoTest.cs (100%) rename Assets/{Editor => }/Tests/Unit/VimeoVideoTest.cs.meta (100%) diff --git a/Assets/Editor.meta b/Assets/Editor.meta deleted file mode 100644 index cb8c0c32..00000000 --- a/Assets/Editor.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 63b999de8039248dc9dc5cd34a784a14 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/Editor/Tests.meta b/Assets/Tests.meta similarity index 100% rename from Assets/Editor/Tests.meta rename to Assets/Tests.meta diff --git a/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta b/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta new file mode 100644 index 00000000..c5b4b457 --- /dev/null +++ b/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta @@ -0,0 +1,22 @@ +fileFormatVersion: 2 +guid: 947491331604da843bf55a919401a3a8 +timeCreated: 1540324736 +licenseType: Pro +VideoClipImporter: + serializedVersion: 2 + useLegacyImporter: 0 + quality: 0.5 + isColorLinear: 0 + frameRange: 0 + startFrame: -1 + endFrame: -1 + colorSpace: 0 + deinterlace: 0 + encodeAlpha: 0 + flipVertical: 0 + flipHorizontal: 0 + importAudio: 1 + targetSettings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/Tests/Play.meta b/Assets/Tests/Play.meta similarity index 100% rename from Assets/Editor/Tests/Play.meta rename to Assets/Tests/Play.meta diff --git a/Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs b/Assets/Tests/Play/AVProMovieCaptureTest.cs similarity index 100% rename from Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs rename to Assets/Tests/Play/AVProMovieCaptureTest.cs diff --git a/Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs.meta b/Assets/Tests/Play/AVProMovieCaptureTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/AVProMovieCaptureTest.cs.meta rename to Assets/Tests/Play/AVProMovieCaptureTest.cs.meta diff --git a/Assets/Editor/Tests/Play/AVProVideoPlayTest.cs b/Assets/Tests/Play/AVProVideoPlayTest.cs similarity index 100% rename from Assets/Editor/Tests/Play/AVProVideoPlayTest.cs rename to Assets/Tests/Play/AVProVideoPlayTest.cs diff --git a/Assets/Editor/Tests/Play/AVProVideoPlayTest.cs.meta b/Assets/Tests/Play/AVProVideoPlayTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/AVProVideoPlayTest.cs.meta rename to Assets/Tests/Play/AVProVideoPlayTest.cs.meta diff --git a/Assets/Editor/Tests/Play/ObjectRotation.cs b/Assets/Tests/Play/ObjectRotation.cs similarity index 100% rename from Assets/Editor/Tests/Play/ObjectRotation.cs rename to Assets/Tests/Play/ObjectRotation.cs diff --git a/Assets/Editor/Tests/Play/ObjectRotation.cs.meta b/Assets/Tests/Play/ObjectRotation.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/ObjectRotation.cs.meta rename to Assets/Tests/Play/ObjectRotation.cs.meta diff --git a/Assets/Editor/Tests/Play/PlayTests.asmdef b/Assets/Tests/Play/PlayTests.asmdef similarity index 100% rename from Assets/Editor/Tests/Play/PlayTests.asmdef rename to Assets/Tests/Play/PlayTests.asmdef diff --git a/Assets/Editor/Tests/Play/PlayTests.asmdef.meta b/Assets/Tests/Play/PlayTests.asmdef.meta similarity index 100% rename from Assets/Editor/Tests/Play/PlayTests.asmdef.meta rename to Assets/Tests/Play/PlayTests.asmdef.meta diff --git a/Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs b/Assets/Tests/Play/VimeoPlayerPlayTest.cs similarity index 100% rename from Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs rename to Assets/Tests/Play/VimeoPlayerPlayTest.cs diff --git a/Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs.meta b/Assets/Tests/Play/VimeoPlayerPlayTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/VimeoPlayerPlayTest.cs.meta rename to Assets/Tests/Play/VimeoPlayerPlayTest.cs.meta diff --git a/Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs similarity index 100% rename from Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs rename to Assets/Tests/Play/VimeoRecorderPlayTest.cs diff --git a/Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs.meta b/Assets/Tests/Play/VimeoRecorderPlayTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/VimeoRecorderPlayTest.cs.meta rename to Assets/Tests/Play/VimeoRecorderPlayTest.cs.meta diff --git a/Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs b/Assets/Tests/Play/VimeoUploaderPlayTest.cs similarity index 100% rename from Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs rename to Assets/Tests/Play/VimeoUploaderPlayTest.cs diff --git a/Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs.meta b/Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Play/VimeoUploaderPlayTest.cs.meta rename to Assets/Tests/Play/VimeoUploaderPlayTest.cs.meta diff --git a/Assets/Editor/Tests/Unit.meta b/Assets/Tests/Unit.meta similarity index 100% rename from Assets/Editor/Tests/Unit.meta rename to Assets/Tests/Unit.meta diff --git a/Assets/Editor/Tests/Unit/UnitTests.asmdef b/Assets/Tests/Unit/UnitTests.asmdef similarity index 100% rename from Assets/Editor/Tests/Unit/UnitTests.asmdef rename to Assets/Tests/Unit/UnitTests.asmdef diff --git a/Assets/Editor/Tests/Unit/UnitTests.asmdef.meta b/Assets/Tests/Unit/UnitTests.asmdef.meta similarity index 100% rename from Assets/Editor/Tests/Unit/UnitTests.asmdef.meta rename to Assets/Tests/Unit/UnitTests.asmdef.meta diff --git a/Assets/Editor/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VideoChunkTest.cs rename to Assets/Tests/Unit/VideoChunkTest.cs diff --git a/Assets/Editor/Tests/Unit/VideoChunkTest.cs.meta b/Assets/Tests/Unit/VideoChunkTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VideoChunkTest.cs.meta rename to Assets/Tests/Unit/VideoChunkTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoPlayerTest.cs b/Assets/Tests/Unit/VimeoPlayerTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoPlayerTest.cs rename to Assets/Tests/Unit/VimeoPlayerTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoPlayerTest.cs.meta b/Assets/Tests/Unit/VimeoPlayerTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoPlayerTest.cs.meta rename to Assets/Tests/Unit/VimeoPlayerTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoPublisherTest.cs b/Assets/Tests/Unit/VimeoPublisherTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoPublisherTest.cs rename to Assets/Tests/Unit/VimeoPublisherTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoPublisherTest.cs.meta b/Assets/Tests/Unit/VimeoPublisherTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoPublisherTest.cs.meta rename to Assets/Tests/Unit/VimeoPublisherTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoRecorderTest.cs b/Assets/Tests/Unit/VimeoRecorderTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoRecorderTest.cs rename to Assets/Tests/Unit/VimeoRecorderTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoRecorderTest.cs.meta b/Assets/Tests/Unit/VimeoRecorderTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoRecorderTest.cs.meta rename to Assets/Tests/Unit/VimeoRecorderTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoSettingsTest.cs b/Assets/Tests/Unit/VimeoSettingsTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoSettingsTest.cs rename to Assets/Tests/Unit/VimeoSettingsTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoSettingsTest.cs.meta b/Assets/Tests/Unit/VimeoSettingsTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoSettingsTest.cs.meta rename to Assets/Tests/Unit/VimeoSettingsTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoUploaderTest.cs rename to Assets/Tests/Unit/VimeoUploaderTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoUploaderTest.cs.meta b/Assets/Tests/Unit/VimeoUploaderTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoUploaderTest.cs.meta rename to Assets/Tests/Unit/VimeoUploaderTest.cs.meta diff --git a/Assets/Editor/Tests/Unit/VimeoVideoTest.cs b/Assets/Tests/Unit/VimeoVideoTest.cs similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoVideoTest.cs rename to Assets/Tests/Unit/VimeoVideoTest.cs diff --git a/Assets/Editor/Tests/Unit/VimeoVideoTest.cs.meta b/Assets/Tests/Unit/VimeoVideoTest.cs.meta similarity index 100% rename from Assets/Editor/Tests/Unit/VimeoVideoTest.cs.meta rename to Assets/Tests/Unit/VimeoVideoTest.cs.meta From 237a52fc10d0d56b9619a94bd9ba84cc4613cd10 Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Tue, 23 Oct 2018 16:17:03 -0400 Subject: [PATCH 64/68] Ignore all mp4 when commiting --- .gitignore | 2 +- .../Heavy_Video_Upload_Test_File.mp4.meta | 22 ------------------- 2 files changed, 1 insertion(+), 23 deletions(-) delete mode 100644 Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta diff --git a/.gitignore b/.gitignore index 3c7318ef..2655e1e1 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ Assets/*TestScene*.unity* TestResults*.xml # Test Assets -Assets/Editor/Tests/*.mp4* +*/*.mp4* # Misc OS files .DS_Store \ No newline at end of file diff --git a/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta b/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta deleted file mode 100644 index c5b4b457..00000000 --- a/Assets/Tests/Heavy_Video_Upload_Test_File.mp4.meta +++ /dev/null @@ -1,22 +0,0 @@ -fileFormatVersion: 2 -guid: 947491331604da843bf55a919401a3a8 -timeCreated: 1540324736 -licenseType: Pro -VideoClipImporter: - serializedVersion: 2 - useLegacyImporter: 0 - quality: 0.5 - isColorLinear: 0 - frameRange: 0 - startFrame: -1 - endFrame: -1 - colorSpace: 0 - deinterlace: 0 - encodeAlpha: 0 - flipVertical: 0 - flipHorizontal: 0 - importAudio: 1 - targetSettings: {} - userData: - assetBundleName: - assetBundleVariant: From 5e74e22441aa70fe3ff16e897e1a3196be303b9f Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Tue, 23 Oct 2018 19:08:33 -0400 Subject: [PATCH 65/68] Add support for resumable chunks (for spotty internet connections) --- Assets/Tests/Unit/VideoChunkTest.cs | 50 +++++++- Assets/Tests/Unit/VimeoUploaderTest.cs | 6 +- Assets/Vimeo/Scripts/Utils/VideoChunk.cs | 139 ++++++++++++++++------- 3 files changed, 147 insertions(+), 48 deletions(-) diff --git a/Assets/Tests/Unit/VideoChunkTest.cs b/Assets/Tests/Unit/VideoChunkTest.cs index 6550cdd4..27c7ffed 100644 --- a/Assets/Tests/Unit/VideoChunkTest.cs +++ b/Assets/Tests/Unit/VideoChunkTest.cs @@ -29,15 +29,16 @@ public void Init_Works() Assert.AreEqual("test_file_path", chunk.filePath); Assert.AreEqual("test_tus_url", chunk.url); - Assert.AreEqual(0, chunk.indexByte); - Assert.AreEqual(10000, chunk.chunkSize); - Assert.AreEqual(chunk.bytes.Length, 10000); + Assert.AreEqual(0, chunk.startByte); + Assert.AreEqual(0, chunk.lastByteUploaded); + Assert.AreEqual(10000, chunk.totalBytes); } [Test] public void Stores_And_Disposes_Bytes() { - chunk.Init(0, "test_tus_url", "test_file_path", 10000); + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 10000); + chunk.ReadBytes(); chunk.bytes[0] = 5; chunk.DisposeBytes(); Assert.AreNotEqual(chunk.bytes[0], 5); @@ -46,9 +47,10 @@ public void Stores_And_Disposes_Bytes() [Test] public void Reads_Bytes_From_File() { - chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1); - Assert.AreEqual(chunk.bytes[0], 0); + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 12412); + Assert.AreEqual(chunk.bytes, null); chunk.ReadBytes(); + Assert.AreEqual(chunk.bytes.Length, 12412); Assert.AreNotEqual(chunk.bytes[0], 0); } @@ -76,6 +78,42 @@ public void GetBytesUploaded_Returns_Uploaded_Bytes_When_Uploading() Assert.AreEqual(chunk.GetBytesUploaded(), 0); } + [Test] + public void UploadError_Retries_Upload() + { + UnityEngine.TestTools.LogAssert.Expect(LogType.Warning, new Regex("Retrying...")); + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1441); + Assert.AreEqual(chunk.totalRetries, 0); + chunk.UploadError("my msg"); + Assert.AreEqual(chunk.totalRetries, 1); + } + + [Test] + public void UploadError_Retries_Three_Times_And_Errors() + { + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, new Regex("it's error time")); + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1441); + Assert.AreEqual(chunk.totalRetries, 0); + chunk.UploadError("my msg"); + Assert.AreEqual(chunk.totalRetries, 1); + chunk.UploadError("my msg"); + Assert.AreEqual(chunk.totalRetries, 2); + chunk.UploadError("my msg"); + Assert.AreEqual(chunk.totalRetries, 3); + + chunk.UploadError("it's error time"); + } + + [Test] + public void Can_Resume_Upload() + { + chunk.Init(0, "test_tus_url", TEST_IMAGE_PATH, 1541); + chunk.lastByteUploaded = 541; + chunk.ReadBytes(); + Assert.AreEqual(chunk.bytes.Length, 1541 - 541); + } + + [TearDown] public void _After() { diff --git a/Assets/Tests/Unit/VimeoUploaderTest.cs b/Assets/Tests/Unit/VimeoUploaderTest.cs index 87ceb9f7..d7e297ad 100644 --- a/Assets/Tests/Unit/VimeoUploaderTest.cs +++ b/Assets/Tests/Unit/VimeoUploaderTest.cs @@ -70,7 +70,7 @@ public void CreateChunks_Makes_One_Chunk_For_Small_Files() uploader.Init("xtokenx", 100000000); uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual(uploader.chunks.Count, 1); - Assert.AreEqual(uploader.chunks[0].chunkSize, testFileSize); + Assert.AreEqual(uploader.chunks[0].totalBytes, testFileSize); } [Test] @@ -86,7 +86,7 @@ public void CreateChunks_Sets_Size_Of_Each_Chunk() { uploader.Init("xtokenx", 1234); uploader.CreateChunks(testFile, "xxx"); - Assert.AreEqual(uploader.chunks[0].chunkSize, 1234); + Assert.AreEqual(uploader.chunks[0].totalBytes, 1234); } [Test] @@ -95,7 +95,7 @@ public void CreateChunks_Last_Chunk_Is_Remainder() uploader.Init("xtokenx", 1000); uploader.CreateChunks(testFile, "xxx"); Assert.AreEqual( - uploader.chunks.ToArray()[uploader.chunks.Count - 1].chunkSize, 879 + uploader.chunks.ToArray()[uploader.chunks.Count - 1].totalBytes, 879 ); } diff --git a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs index 89a9fd43..ca1743b6 100644 --- a/Assets/Vimeo/Scripts/Utils/VideoChunk.cs +++ b/Assets/Vimeo/Scripts/Utils/VideoChunk.cs @@ -10,12 +10,22 @@ namespace Vimeo { public class VideoChunk : MonoBehaviour { - private int m_indexByte; - public int indexByte { + private long m_startByte; + public long startByte { get { - return m_indexByte; + return m_startByte; } } + private long m_lastByteUploaded; + public long lastByteUploaded { + get { + return m_lastByteUploaded; + } + set { + m_lastByteUploaded = value; + } + } + private string m_url; public string url { get { @@ -30,10 +40,10 @@ public string filePath { } } - private int m_chunkSize; - public int chunkSize { + private int m_totalBytes; + public int totalBytes { get { - return m_chunkSize; + return m_totalBytes; } } @@ -60,26 +70,34 @@ public bool isFinishedUploading { public event UploadEvent OnChunkUploadComplete; public event UploadEvent OnChunkUploadError; - private UnityWebRequest m_chunkUploadRequest; - public UnityWebRequest chunkUploadRequest { + private UnityWebRequest m_uploadRequest; + public UnityWebRequest uploadRequest { get { - return m_chunkUploadRequest; + return m_uploadRequest; } } - public void Init(int _indexByte, string _url, string _filePath, int _chunkSize) + private int maxRetries = 3; + private int m_totalRetries = 0; + public int totalRetries { + get { + return m_totalRetries; + } + } + + public void Init(int _startByte, string _url, string _filePath, int _totalBytes) { - m_chunkSize = _chunkSize; + m_totalBytes = _totalBytes; m_filePath = _filePath; - m_indexByte = _indexByte; + m_lastByteUploaded = m_startByte = _startByte; m_url = _url; - bytes = new byte[m_chunkSize]; } public void ReadBytes() { + bytes = new byte[m_totalBytes - (lastByteUploaded - startByte)]; using (BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))) { - reader.BaseStream.Seek(m_indexByte, SeekOrigin.Begin); + reader.BaseStream.Seek(m_lastByteUploaded, SeekOrigin.Begin); reader.Read(bytes, 0, bytes.Length); } } @@ -92,39 +110,82 @@ public void DisposeBytes() private IEnumerator SendTusRequest() { ReadBytes(); - using (UnityWebRequest uploadRequest = UnityWebRequest.Put(m_url, bytes)) { - uploadRequest.chunkedTransfer = false; - uploadRequest.method = "PATCH"; - uploadRequest.SetRequestHeader("Tus-Resumable", "1.0.0"); - uploadRequest.SetRequestHeader("Upload-Offset", (m_indexByte).ToString()); - uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); - m_chunkUploadRequest = uploadRequest; - m_isUploading = true; - - yield return VimeoApi.SendRequest(uploadRequest); - - if (uploadRequest.isNetworkError || uploadRequest.isHttpError) { - m_isUploading = false; - if (OnChunkUploadError != null) { - OnChunkUploadError(this, "[Error] " + uploadRequest.error + " error code is: " + uploadRequest.responseCode); - } - } else { - m_isUploading = false; - m_isFinishedUploading = true; - if (OnChunkUploadComplete != null) { - OnChunkUploadComplete(this, uploadRequest.GetResponseHeader("Upload-Offset")); - } + + m_uploadRequest = UnityWebRequest.Put(m_url, bytes); + SetupTusRequest(m_uploadRequest); + m_uploadRequest.method = "PATCH"; + m_uploadRequest.SetRequestHeader("Upload-Offset", m_lastByteUploaded.ToString()); + m_uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); + + m_isUploading = true; + + yield return VimeoApi.SendRequest(m_uploadRequest); + + if (m_uploadRequest.isNetworkError || m_uploadRequest.isHttpError) { + UploadError(m_uploadRequest.responseCode + ": " + m_uploadRequest.error); + } else { + m_isUploading = false; + m_isFinishedUploading = true; + if (OnChunkUploadComplete != null) { + OnChunkUploadComplete(this, m_uploadRequest.GetResponseHeader("Upload-Offset")); + } + } + + DisposeBytes(); + } + + public void UploadError(string msg) + { + if (m_totalRetries >= maxRetries) { + m_isUploading = false; + Debug.LogError("[VideoChunk] " + msg); + + if (OnChunkUploadError != null) { + OnChunkUploadError(this, msg); } } + else { + Debug.LogWarning("[VideoChunk] " + msg + " - Retrying..."); + m_totalRetries++; + StartCoroutine(ResumeUpload()); + } + } + + private IEnumerator ResumeUpload() + { + yield return new WaitForSeconds(5); // Wait a bit before trying again so there is time to reconnect + + // Make a request to check what the last upload offset is... + UnityWebRequest uploadCheck = UnityWebRequest.Get(m_url); + uploadCheck.method = "HEAD"; + SetupTusRequest(uploadCheck); + + yield return VimeoApi.SendRequest(uploadCheck); + + if (uploadCheck.GetResponseHeader("Upload-Offset") != null) { + m_lastByteUploaded = long.Parse(uploadCheck.GetResponseHeader("Upload-Offset")); + } + + uploadCheck.Dispose(); + m_uploadRequest.Dispose(); + m_uploadRequest = null; DisposeBytes(); + Upload(); + } + + private void SetupTusRequest(UnityWebRequest r) + { + r.chunkedTransfer = false; + r.SetRequestHeader("Tus-Resumable", "1.0.0"); + r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=3.4"); } public ulong GetBytesUploaded() { - if (m_isUploading && m_chunkUploadRequest != null) { - return m_chunkUploadRequest.uploadedBytes; + if (m_isUploading && m_uploadRequest != null) { + return m_uploadRequest.uploadedBytes; } else if (m_isFinishedUploading) { - return (ulong)m_chunkSize; + return (ulong)totalBytes; } return 0; } From 97d5f3de1ddc103caa9d8a104cea9a1c6cda3d3b Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 24 Oct 2018 11:04:39 -0400 Subject: [PATCH 66/68] Updating it so it should ignore the meta file created for the video as well as the video itself inside the Tests folder --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2655e1e1..2f5d0f38 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ Assets/*TestScene*.unity* TestResults*.xml # Test Assets -*/*.mp4* +*/*/*.mp4* # Misc OS files .DS_Store \ No newline at end of file From 1ebaa82948ae8994f5398ec15f676b77bd48c35e Mon Sep 17 00:00:00 2001 From: juniorxsound Date: Wed, 24 Oct 2018 11:06:10 -0400 Subject: [PATCH 67/68] Updating gitignore to ignore all mp4's and meta files created by Unity --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2f5d0f38..65dde709 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ Assets/*TestScene*.unity* TestResults*.xml # Test Assets -*/*/*.mp4* +**/*.mp4* # Misc OS files .DS_Store \ No newline at end of file From 9732b46c891d4f49d399d3e17ad6133bf340b1a7 Mon Sep 17 00:00:00 2001 From: Casey Pugh Date: Wed, 24 Oct 2018 11:29:29 -0400 Subject: [PATCH 68/68] Move version init to _Before --- Assets/Tests/Play/VimeoRecorderPlayTest.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Assets/Tests/Play/VimeoRecorderPlayTest.cs b/Assets/Tests/Play/VimeoRecorderPlayTest.cs index 32469e5f..6c489369 100644 --- a/Assets/Tests/Play/VimeoRecorderPlayTest.cs +++ b/Assets/Tests/Play/VimeoRecorderPlayTest.cs @@ -21,11 +21,13 @@ public class VimeoRecorderPlayTest : TestConfig bool finished; bool error; - string version = "(" + Application.platform + " " + Application.unityVersion + ")"; + string version; [SetUp] public void _Before() { + version = "(" + Application.platform + " " + Application.unityVersion + ")"; + // Setup cube cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.AddComponent();