public async Task <DiagnosisKey> AddDiagnosisKey(DiagnosisKey newDiagnosisKey)
        {
            await _context.DiagnosisKeys.AddAsync(newDiagnosisKey);

            await _context.SaveChangesAsync();

            return(newDiagnosisKey);
        }
Ejemplo n.º 2
0
        public async Task DeleteVideoAsync(CTDbContext context)
        {
            if (Video1 != null)
            {
                await Video1.DeleteFileRecordAsync(context);
            }
            if (Video2 != null)
            {
                await Video2.DeleteFileRecordAsync(context);
            }
            if (ProcessedVideo1 != null)
            {
                await ProcessedVideo1.DeleteFileRecordAsync(context);
            }
            if (ProcessedVideo2 != null)
            {
                await ProcessedVideo2.DeleteFileRecordAsync(context);
            }
            if (Audio != null)
            {
                await Audio.DeleteFileRecordAsync(context);
            }
            var dbVideoRow = await context.Videos.FindAsync(Id);

            if (dbVideoRow != null)
            {
                context.Videos.Remove(dbVideoRow);
                await context.SaveChangesAsync();
            }
        }
Ejemplo n.º 3
0
        public async Task <ApplicationUser> CreateNonExistentUser(string emailId)
        {
            ApplicationUser user = new ApplicationUser
            {
                EmailConfirmed = false,
                UserName       = emailId,
                Email          = emailId
            };
            var result = await _userManager.CreateAsync(user, user.Email);

            University university = await GetUniversity(user.Email);

            user.University = university;
            await _context.SaveChangesAsync();

            return(await _userManager.FindByEmailAsync(emailId));
        }
Ejemplo n.º 4
0
        public async Task Subscribe(Entity entity, ApplicationUser user)
        {
            Subscription subscription = new Subscription
            {
                ApplicationUserId = user.Id,
                ResourceType      = entity.GetResourceType(),
                ResourceId        = entity.Id
            };

            if (!(await _context.Subscriptions.AnyAsync(s => s.ResourceType == subscription.ResourceType &&
                                                        s.ResourceId == subscription.ResourceId &&
                                                        s.ApplicationUserId == subscription.ApplicationUserId)))
            {
                _context.Subscriptions.Add(subscription);
            }
            await _context.SaveChangesAsync();
        }
Ejemplo n.º 5
0
        /// For recently directly/manually uploaded video files,
        /// only the media entry for each uploaded video is created
        /// But we process them here AND in the DownloadMedia
        /// (which ultimately sets the name)
        /// i.e. to better understand this code first also read the DownloadMedia code
        /// When run as part of the periodic update all playlists, this
        /// code should be a NOOP
        public async Task <List <Media> > GetLocalPlaylist(Playlist playlist, CTDbContext _context)
        {
            var medias = await _context.Medias.Where(m => m.Video == null && m.PlaylistId == playlist.Id).ToListAsync();

            medias.ForEach(m => m.Name = GetMediaName(m));
            await _context.SaveChangesAsync();

            return(medias);
        }
Ejemplo n.º 6
0
        public async Task <List <Media> > GetYoutubePlaylist(Playlist playlist, CTDbContext _context)
        {
            List <Media> newMedia = new List <Media>();

            CTGrpc.JsonString jsonString = null;
            CTGrpc.JsonString metadata   = new CTGrpc.JsonString
            {
                Json = playlist.JsonMetadata != null?playlist.JsonMetadata.ToString() : ""
            };
            try
            {
                jsonString = await _rpcClient.PythonServerClient.GetYoutubePlaylistRPCAsync(new CTGrpc.PlaylistRequest
                {
                    Url      = playlist.PlaylistIdentifier,
                    Metadata = metadata
                });
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode == StatusCode.InvalidArgument)
                {
                    if (e.Status.Detail == "INVALID_PLAYLIST_IDENTIFIER")
                    {
                        // Notification to Instructor.
                    }
                    GetLogger().LogError(e.Message);
                }
                return(newMedia);
            }
            JArray jArray = JArray.Parse(jsonString.Json);

            foreach (JObject jObject in jArray)
            {
                // Check if there is a valid videoId, and for the same playlist the same media does not exist.
                if (jObject["videoId"].ToString().Length > 0 &&
                    !await _context.Medias.Where(m => m.UniqueMediaIdentifier == jObject["videoId"].ToString() &&
                                                 m.SourceType == playlist.SourceType &&
                                                 m.PlaylistId == playlist.Id).AnyAsync())
                {
                    newMedia.Add(new Media
                    {
                        JsonMetadata          = jObject,
                        SourceType            = playlist.SourceType,
                        PlaylistId            = playlist.Id,
                        UniqueMediaIdentifier = jObject["videoId"].ToString()
                    });
                }
            }
            newMedia.ForEach(m => m.Name = GetMediaName(m));
            await _context.Medias.AddRangeAsync(newMedia);

            await _context.SaveChangesAsync();

            return(newMedia);
        }
        public async Task <IActionResult> PostWatchHistory(string mediaId, JObject json)
        {
            var media = await _context.Medias.FindAsync(mediaId);

            if (media == null || json == null)
            {
                return(BadRequest());
            }
            var user = await _userUtils.GetUser(User);

            if (user != null)
            {
                var watchHistory = await _context.WatchHistories
                                   .Where(w => w.MediaId == mediaId && w.ApplicationUserId == user.Id)
                                   .FirstOrDefaultAsync();

                if (watchHistory == null)
                {
                    watchHistory = new WatchHistory
                    {
                        ApplicationUserId = user.Id,
                        MediaId           = mediaId,
                        Json = json
                    };
                    await _context.WatchHistories.AddAsync(watchHistory);
                }
                else
                {
                    watchHistory.Json = json;
                    _context.Entry(watchHistory).State = EntityState.Modified;
                }

                await _context.SaveChangesAsync();
            }
            else
            {
                return(Unauthorized());
            }
            return(NoContent());
        }
        public async Task <List <Media> > GetKalturaPlaylist(Playlist playlist, CTDbContext _context)
        {
            List <Media> newMedia = new List <Media>();

            CTGrpc.JsonString jsonString = null;
            try
            {
                jsonString = await _rpcClient.PythonServerClient.GetKalturaChannelEntriesRPCAsync(new CTGrpc.PlaylistRequest
                {
                    Url = playlist.PlaylistIdentifier
                });
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode == StatusCode.InvalidArgument)
                {
                    if (e.Status.Detail == "INVALID_PLAYLIST_IDENTIFIER")
                    {
                        // Notification to Instructor.
                    }
                    _logger.LogError(e.Message);
                }
                return(newMedia);
            }
            JArray jArray = JArray.Parse(jsonString.Json);

            foreach (JObject jObject in jArray)
            {
                // Check if there is a valid Id, and for the same playlist the same media does not exist.
                if (jObject["id"].ToString().Length > 0 &&
                    !await _context.Medias.Where(m => m.UniqueMediaIdentifier == jObject["id"].ToString() &&
                                                 m.SourceType == playlist.SourceType &&
                                                 m.PlaylistId == playlist.Id).AnyAsync())
                {
                    newMedia.Add(new Media
                    {
                        JsonMetadata          = jObject,
                        SourceType            = playlist.SourceType,
                        PlaylistId            = playlist.Id,
                        UniqueMediaIdentifier = jObject["id"].ToString(),
                        CreatedAt             = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                                                .AddSeconds(jObject["createdAt"].ToObject <int>())
                    });
                }
            }
            newMedia.ForEach(m => m.Name = GetMediaName(m));
            await _context.Medias.AddRangeAsync(newMedia);

            await _context.SaveChangesAsync();

            return(newMedia);
        }
Ejemplo n.º 9
0
        private async Task <List <Media> > GetBoxPlaylist(Playlist playlist, CTDbContext _context)
        {
            try
            {
                var client = await _box.GetBoxClientAsync();

                /// Try to refresh the access token
                var folderInfo = await client.FoldersManager.GetInformationAsync(playlist.PlaylistIdentifier);

                playlist.JsonMetadata = JObject.FromObject(folderInfo);

                var items = (await client.FoldersManager.GetFolderItemsAsync(playlist.PlaylistIdentifier, 500)).Entries.OfType <BoxFile>();
                // Process only files with an mp4 extension.
                items = items.Where(i => i.Name.Substring(i.Name.LastIndexOf(".") + 1) == "mp4").ToList();
                List <Media> newMedia = new List <Media>();

                foreach (var item in items)
                {
                    var file = await client.FilesManager.GetInformationAsync(item.Id);

                    // Check if there is a valid file.Id, and for the same playlist the same media does not exist.
                    if (file.Id.Length > 0 &&
                        !await _context.Medias.Where(m => m.UniqueMediaIdentifier == file.Id &&
                                                     m.SourceType == playlist.SourceType &&
                                                     m.PlaylistId == playlist.Id).AnyAsync())
                    {
                        newMedia.Add(new Media
                        {
                            SourceType            = playlist.SourceType,
                            PlaylistId            = playlist.Id,
                            UniqueMediaIdentifier = file.Id,
                            JsonMetadata          = JObject.FromObject(file),
                            CreatedAt             = file.CreatedAt ?? DateTime.Now
                        });
                    }
                }
                newMedia.ForEach(m => m.Name = GetMediaName(m));
                await _context.Medias.AddRangeAsync(newMedia);

                await _context.SaveChangesAsync();

                return(newMedia);
            }
            catch (Box.V2.Exceptions.BoxSessionInvalidatedException e)
            {
                GetLogger().LogError(e, "Box Token Failure.");
                await _slack.PostErrorAsync(e, "Box Token Failure.");

                throw;
            }
        }
Ejemplo n.º 10
0
        // The following is impossible because rpcClient is in the CTCommons project
        // which depends on this project, not the other way around

        //bool useRPCForFileDigest = false;
        //if(useRPCForFileDigest)
        //{
        //    var request = new CTGrpc.FileHashRequest
        //    {
        //        File = filePath,
        //        Algorithms = "sha256"
        //    };
        //    CTGrpc.FileHashResponse rpcresponse = await _rpcClient.PythonServerClient(request);
        //    return rpcresponse.Result;
        // }
        // ComputeHashAsync is not yet available (only in 5.0 RC1)
        //
        // The concern is that ComputeHash is hogging the thread for too long
        // So async tasks (e.g. SpeechToText might timeout)



        /// <summary>
        /// Delete a file record, and its corresponding file.
        /// </summary>
        public async Task DeleteFileRecordAsync(CTDbContext context)
        {
            if (File.Exists(Path))
            {
                File.Delete(Path);
            }
            var dbFileRecord = await context.FileRecords.FindAsync(Id);

            if (dbFileRecord != null)
            {
                context.FileRecords.Remove(dbFileRecord);
                await context.SaveChangesAsync();
            }
        }
Ejemplo n.º 11
0
        private async Task TestYoutubeChannelDownload()
        {
            Playlist p = new Playlist
            {
                JsonMetadata = new JObject
                {
                    { "isChannel", "1" }
                },
                PlaylistIdentifier = "UCi8e0iOVk1fEOogdfu4YgfA" // change me - too many videos
            };

            context.Playlists.Add(p);
            await context.SaveChangesAsync();

            //p.Id = "72336862-244c-4904-a753-2f620ae99633";
            _downloadPlaylistInfoTask.Publish(p.Id);
        }
Ejemplo n.º 12
0
        public async Task <List <Media> > GetEchoPlaylist(Playlist playlist, CTDbContext _context)
        {
            List <Media> newMedia = new List <Media>();

            CTGrpc.JsonString jsonString = null;
            try
            {
                jsonString = await _rpcClient.PythonServerClient.GetEchoPlaylistRPCAsync(new CTGrpc.PlaylistRequest
                {
                    Url    = playlist.PlaylistIdentifier,
                    Stream = 0
                });
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode == StatusCode.InvalidArgument)
                {
                    if (e.Status.Detail == "INVALID_PLAYLIST_IDENTIFIER")
                    {
                        // Notification to Instructor.
                    }
                    GetLogger().LogError(e.Message);
                }
                return(newMedia);
            }
            JObject res = JObject.Parse(jsonString.Json);

            // Add DownloadHeader to playlist, required for downloading media.
            if (playlist.JsonMetadata == null)
            {
                playlist.JsonMetadata = new JObject();
            }

            if (playlist.JsonMetadata.ContainsKey("downloadHeader"))
            {
                playlist.JsonMetadata["downloadHeader"] = res["downloadHeader"].ToString();
            }
            else
            {
                playlist.JsonMetadata.Add("downloadHeader", res["downloadHeader"].ToString());
            }

            JArray jArray = res["medias"] as JArray;


            foreach (JObject jObject in jArray)
            {
                // Check if there is a valid Id, and for the same playlist the same media does not exist.
                if (jObject["mediaId"].ToString().Length > 0 &&
                    !await _context.Medias.Where(m => m.UniqueMediaIdentifier == jObject["mediaId"].ToString() &&
                                                 m.SourceType == playlist.SourceType &&
                                                 m.PlaylistId == playlist.Id).AnyAsync())
                {
                    newMedia.Add(new Media
                    {
                        JsonMetadata          = jObject,
                        SourceType            = playlist.SourceType,
                        PlaylistId            = playlist.Id,
                        UniqueMediaIdentifier = jObject["mediaId"].ToString(),
                        CreatedAt             = Convert.ToDateTime(jObject["createdAt"], CultureInfo.InvariantCulture)
                    });
                }
            }
            newMedia.ForEach(m => m.Name = GetMediaName(m));
            await _context.Medias.AddRangeAsync(newMedia);

            await _context.SaveChangesAsync();

            return(newMedia);
        }