示例#1
0
 public ConvTask(DbCtx dbctx, Track track, MCloudConfig.Converter conv, ILogger <ConvertService> logger)
 {
     Dbctx       = dbctx;
     Track       = track;
     Conv        = conv;
     this.logger = logger;
 }
示例#2
0
 public MessageService(IServiceProvider services, ILogger <MessageService> logger)
 {
     this.scope   = services.CreateScope();
     this.dbCtx   = scope.ServiceProvider.GetService <DbCtx>();
     this.logger  = logger;
     this.clients = new List <Client>();
 }
示例#3
0
        public async Task <ConvResult> GetConverted(DbCtx dbctx, Track track, MCloudConfig.Converter conv)
        {
            var taskKey = track.id + "-" + conv.Name;
            var task    = tasks.GetOrAdd(taskKey, (key) =>
            {
                return(new ConvTask(dbctx, track, conv, logger));
            });

            try
            {
                logger.LogInformation("'{taskKey}' start convert", taskKey);
                await task.Run(out var alreadyRunning);

                logger.LogInformation("'{taskKey}' end (already existed = {val})", taskKey, alreadyRunning);
                return(new ConvResult
                {
                    TrackFile = task.TrackFile,
                    AlreadyExisted = alreadyRunning
                });
            }
            finally
            {
                tasks.TryRemove(taskKey, out _);
            }
        }
示例#4
0
        public static async Task <GetLoginResult> GetLoginFromToken(DbCtx dbctx, string auth)
        {
            LoginRecord record = null;
            User        user   = null;

            var splits = auth.Split(' ');

            if (splits.Length != 2)
            {
                return(default);
示例#5
0
 private void AppCheckFirstRun(AppService appService, DbCtx dbctx, ILogger <Startup> logger)
 {
     if (dbctx.Users.Count() == 0)
     {
         logger.LogInformation("No user is found, creating the default \"admin\" user.");
         var user = new User {
             username = "******",
             passwd   = Utils.HashPassword("admin"),
             lists    = new List <int>(),
             role     = UserRole.SuperAdmin
         };
         dbctx.Users.Add(user);
         dbctx.SaveChanges();
         dbctx.Entry(user).State = EntityState.Detached;
     }
 }
示例#6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AppService appService, DbCtx dbctx, ILogger <Startup> logger)
        {
            app.UseForwardedHeaders();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            dbctx.Database.Migrate();
            AppMigrate(appService, dbctx, logger).Wait();
            AppCheckFirstRun(appService, dbctx, logger);

            if (string.IsNullOrEmpty(MyConfigration.Passcode) == false)
            {
                app.UsePasscode(new SimplePasscodeOptions
                {
                    CookieName = "mcloud_passcode",
                    Passcode   = MyConfigration.Passcode,
                    Filter     = ctx => !ctx.Request.Path.StartsWithSegments("/api/storage") &&
                                 !ctx.Request.Path.StartsWithSegments("/.well-known")
                });
            }

            if (MyConfigration.StaticDir != null)
            {
                var fileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), MyConfigration.StaticDir));
                app.UseDefaultFiles(new DefaultFilesOptions
                {
                    FileProvider     = fileProvider,
                    DefaultFileNames = new[] { "index.html" }
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider          = fileProvider,
                    ServeUnknownFileTypes = true
                });
            }

            if (string.IsNullOrEmpty(MyConfigration.StorageDir) == false)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), MyConfigration.StorageDir);
                Directory.CreateDirectory(path);
                var fp = new StaticFileOptions
                {
                    FileProvider          = new PhysicalFileProvider(path),
                    RequestPath           = "/api/storage",
                    ServeUnknownFileTypes = true
                };
                app.Use(async(ctx, next) =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api/storage"))
                    {
                        ctx.Response.Headers.Add("Cache-Control", "public");
                    }
                    await next();
                });
                app.UseStaticFiles(fp);
            }

            app.Use((ctx, next) =>
            {
                if (ctx.Request.Path.StartsWithSegments("/api/my", out var remaining))
                {
                    ctx.Request.Path = "/api/users/me" + remaining;
                }
                return(next());
            });

            app.UseWebSockets();

            app.Use((next) => async(ctx) =>
            {
                if (ctx.Request.Path == "/api/ws" && ctx.WebSockets.IsWebSocketRequest)
                {
                    var ws = await ctx.WebSockets.AcceptWebSocketAsync();
                    await ctx.RequestServices.GetService <MessageService>().HandleWebSocket(ws);
                }
                else
                {
                    await next(ctx);
                }
            });

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
示例#7
0
        private async Task AppMigrate(AppService appService, DbCtx dbctx, ILogger logger)
        {
            dbctx.Database.BeginTransaction();
            var val = await dbctx.GetConfig("appver");

            var origVal = val;

            // if (val == null)
            // {
            //     val = "1";
            // }
            // if (val == "1")
            // {
            //     int count = 0;
            //     foreach (var item in dbctx.Tracks.AsNoTracking())
            //     {
            //         try
            //         {
            //             if (item.TryGetStoragePath(appService, out var path))
            //             {
            //                 item.size = (int)new FileInfo(path).Length;
            //                 dbctx.Entry(item).State = EntityState.Modified;
            //                 if (++count % 100 == 0) await dbctx.SaveChangesAsync();
            //             }
            //         }
            //         catch (System.Exception ex)
            //         {
            //             logger.LogWarning(ex, "getting file length from track id {id}", item.id);
            //         }
            //     }
            //     await dbctx.SaveChangesAsync();
            //     logger.LogInformation("saved file length for {count} files", count);
            //     val = "2";
            // }
            // if (val == "2") {
            //     await dbctx.Database.ExecuteSqlRawAsync("UPDATE tracks SET album = \"\", albumArtist = \"\", groupId = id;");
            //     val = "3";
            // }
            // if (val == "3") {
            //     int count = 0;
            //     foreach (var track in dbctx.Tracks.Include(t => t.fileRecord))
            //     {
            //         track.fileRecord = new StoredFile {
            //             path = track.url,
            //             size = track.size
            //         };
            //         if (track.files != null)
            //             track.trackFiles = track.files.Select(x => {
            //                 var cloned = x.Clone();
            //                 cloned.Track = track;
            //                 cloned.File = new StoredFile {
            //                     path = track.url + "." + cloned.ConvName,
            //                     size = cloned.Size
            //                 };
            //                 return cloned;
            //             }).ToList();
            //         else
            //             track.trackFiles = new List<TrackFile>();
            //         track.trackFiles.Insert(0, new TrackFile{
            //             Track = track,
            //             ConvName = "",
            //             Bitrate = track.length == 0 ? 0 : (int)(track.fileRecord.size * 8 / track.length / 1024),
            //             File = track.fileRecord,
            //             Format = track.fileRecord.path.Substring(track.fileRecord.path.LastIndexOf('.') + 1)
            //         });
            //         dbctx.TrackFiles.AddRange(track.trackFiles);
            //         dbctx.Files.AddRange(track.trackFiles.Select(t => t.File));
            //         dbctx.Entry(track).State = EntityState.Modified;
            //         if (++count % 100 == 0) await dbctx.SaveChangesAsync();
            //     }
            //     await dbctx.SaveChangesAsync();
            //     logger.LogInformation("updated StoredFile for {count} tracks", count);
            //     val = "4";
            // }
            if (val == null)
            {
                val = "4";
            }
            if (val != "4")
            {
                throw new Exception($"Unsupported appver \"{val}\"");
            }
            if (val != origVal)
            {
                logger.LogInformation("appver changed from {orig} to {val}", origVal, val);
                await dbctx.SetConfig("appver", val);
            }
            dbctx.Database.CommitTransaction();
        }
示例#8
0
 public UserService(DbCtx dbctx)
 {
     this.dbctx        = dbctx;
     dbctx.UserService = this;
 }