feat: 初回コミット (MusicStreaming)

This commit is contained in:
armonica committed 2026-10-01 09:42:57 +09:00
commit cb24486e50
45 files changed
+3318

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
## Visual Studio 2026 / .NET .gitignore
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
.vs/
*.user
*.suo
*.userosscache
*.sln.docstates
+1
View File
@@ -0,0 +1 @@

+3
View File
@@ -0,0 +1,3 @@
<Solution>
<Project Path="MusicStreaming/MusicStreaming.csproj" />
</Solution>
+17
View File
@@ -0,0 +1,17 @@
namespace MusicStreaming.Class.Models;
/// <summary>
/// LRC 歌詞の1行を表すモデルクラス
/// </summary>
public class LyricLine
{
/// <summary>
/// 再生開始時間(秒)
/// </summary>
public double TimeSeconds { get; set; }
/// <summary>
/// 歌詞テキスト
/// </summary>
public string Text { get; set; } = string.Empty;
}
@@ -0,0 +1,58 @@
namespace MusicStreaming.Class.Models;
/// <summary>
/// プレイリスト情報を表すモデルクラス
/// </summary>
public class PlaylistItem
{
/// <summary>
/// プレイリストの一意なID
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// プレイリスト表示名(例: "Granblue Fantasy OST", "ボーカル", "すべての曲")
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 元となる .m3u8 ファイル名(自動生成プレイリストの場合は null)
/// </summary>
public string? FileName { get; set; }
/// <summary>
/// 収録トラック数
/// </summary>
public int TrackCount => Tracks.Count;
/// <summary>
/// 総再生時間(秒)
/// </summary>
public int TotalDurationSeconds => Tracks.Sum(t => t.DurationSeconds);
/// <summary>
/// フォーマット済み総再生時間(例: "1時間25分" または "45分10秒")
/// </summary>
public string TotalDurationFormatted
{
get
{
var ts = TimeSpan.FromSeconds(TotalDurationSeconds);
if (ts.TotalHours >= 1)
{
return $"{Math.Floor(ts.TotalHours)}時間{ts.Minutes}分";
}
return $"{ts.Minutes}分{ts.Seconds}秒";
}
}
/// <summary>
/// UI表示用の動的CSSグラデーション
/// </summary>
public string CoverGradient { get; set; } = "linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)";
/// <summary>
/// 含まれるトラックのリスト
/// </summary>
public List<TrackItem> Tracks { get; set; } = new();
}
+72
View File
@@ -0,0 +1,72 @@
namespace MusicStreaming.Class.Models;
/// <summary>
/// 楽曲トラック情報を表すモデルクラス
/// </summary>
public class TrackItem
{
/// <summary>
/// 一意な楽曲ID(相対パスのハッシュなど)
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// 曲名(タイトル)
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// アーティスト名またはサークル名
/// </summary>
public string Artist { get; set; } = string.Empty;
/// <summary>
/// アルバム名または所属プレイリスト名
/// </summary>
public string Album { get; set; } = string.Empty;
/// <summary>
/// 再生時間(秒数)
/// </summary>
public int DurationSeconds { get; set; }
/// <summary>
/// フォーマット済み再生時間(例: "3:45")
/// </summary>
public string DurationFormatted => TimeSpan.FromSeconds(DurationSeconds).ToString(DurationSeconds >= 3600 ? @"h\:mm\:ss" : @"m\:ss");
/// <summary>
/// ライブラリ基準の相対パス(例: "Youtube/song.opus")
/// </summary>
public string RelativePath { get; set; } = string.Empty;
/// <summary>
/// ホスト上の絶対ファイルパス
/// </summary>
public string FullPath { get; set; } = string.Empty;
/// <summary>
/// 同名の歌詞ファイル(.lrc)が存在するかどうか
/// </summary>
public bool HasLyrics { get; set; }
/// <summary>
/// Google Drive のファイルID(ストリーミング配信用)
/// </summary>
public string GoogleDriveFileId { get; set; } = string.Empty;
/// <summary>
/// Google Drive 上の歌詞ファイル(.lrc)のファイルID
/// </summary>
public string? LrcFileId { get; set; }
/// <summary>
/// ファイルサイズ(バイト)
/// </summary>
public long FileSize { get; set; }
/// <summary>
/// 最終更新日時
/// </summary>
public DateTime LastModified { get; set; }
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,470 @@
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using MusicStreaming.Class.Models;
namespace MusicStreaming.Class.Services;
/// <summary>
/// Google Drive のメタデータアイテム情報
/// </summary>
public record GoogleDriveItem(string id, string local_title, long file_size, string type);
/// <summary>
/// Google Drive 共有フォルダと連携してライブラリ・プレイリスト・歌詞を管理するサービス
/// </summary>
public class MusicLibraryService
{
private readonly ILogger<MusicLibraryService> _logger;
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _httpClientFactory;
private readonly string _googleDriveFolderId;
private readonly string _indexPath;
// キャッシュ保持
private readonly ConcurrentDictionary<string, PlaylistItem> _playlists = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, TrackItem> _tracksById = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<string, List<LyricLine>> _lyricsCache = new(StringComparer.OrdinalIgnoreCase);
// Google Drive アイテムマップ (ファイル名 -> GoogleDriveItem)
private readonly ConcurrentDictionary<string, GoogleDriveItem> _itemsByFileName = new(StringComparer.OrdinalIgnoreCase);
private readonly SemaphoreSlim _scanLock = new(1, 1);
private DateTime _lastScanTime = DateTime.MinValue;
public string? LastScanError { get; private set; }
public string GoogleDriveFolderId => _googleDriveFolderId;
public DateTime LastScanTime => _lastScanTime;
// プレイリスト用グラデーションパレット
private static readonly string[] Gradients = new[]
{
"linear-gradient(135deg, #e52d27 0%, #b31217 100%)", // YouTube Red
"linear-gradient(135deg, #1f4037 0%, #99f2c8 100%)", // Emerald
"linear-gradient(135deg, #654ea3 0%, #eaafc8 100%)", // Purple/Pink
"linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)", // Royal Blue
"linear-gradient(135deg, #f12711 0%, #f5af19 100%)", // Fire Orange
"linear-gradient(135deg, #833ab4 0%, #fd1d1d 50%, #fcb045 100%)", // Sunset
"linear-gradient(135deg, #000428 0%, #004e92 100%)", // Deep Ocean
"linear-gradient(135deg, #4b6cb7 0%, #182848 100%)" // Midnight
};
public MusicLibraryService(ILogger<MusicLibraryService> logger, IConfiguration configuration, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_googleDriveFolderId = _configuration["MusicLibrary:GoogleDriveFolderId"] ?? "19cEGl5nAToDSdlBOkB3vr6-emoF-B86g";
_indexPath = Path.Combine(AppContext.BaseDirectory, "google_drive_index.json");
}
/// <summary>
/// ライブラリの初期化・スキャンを実行します
/// </summary>
public async Task InitializeAsync()
{
await ScanLibraryAsync();
}
/// <summary>
/// Google Drive のインデックスおよびプレイリストをスキャンしてライブラリを構築します
/// </summary>
public async Task ScanLibraryAsync()
{
await _scanLock.WaitAsync();
try
{
_logger.LogInformation("Google Drive 音楽ライブラリのスキャンを開始します: FolderId={FolderId}", _googleDriveFolderId);
try
{
// 1. google_drive_index.json から Google Drive 上のファイルマップを読み込み
if (!File.Exists(_indexPath))
{
LastScanError = $"Index file not found: {_indexPath}";
_logger.LogWarning("インデックスファイルが見つかりません: {Path}", _indexPath);
return;
}
var jsonContent = await File.ReadAllTextAsync(_indexPath, Encoding.UTF8);
var items = JsonSerializer.Deserialize<List<GoogleDriveItem>>(jsonContent, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (items == null || items.Count == 0)
{
LastScanError = "Index file contains no items";
_logger.LogWarning("インデックスファイルにアイテムが含まれていません: {Path}", _indexPath);
return;
}
_itemsByFileName.Clear();
var m3u8Items = new List<GoogleDriveItem>();
var lrcByBaseName = new ConcurrentDictionary<string, GoogleDriveItem>(StringComparer.OrdinalIgnoreCase);
foreach (var item in items)
{
var fileName = item.local_title.Trim();
_itemsByFileName[fileName] = item;
if (item.type == "m3u8" || fileName.EndsWith(".m3u8", StringComparison.OrdinalIgnoreCase))
{
m3u8Items.Add(item);
}
else if (item.type == "lrc" || fileName.EndsWith(".lrc", StringComparison.OrdinalIgnoreCase))
{
var baseName = Path.GetFileNameWithoutExtension(fileName);
lrcByBaseName[baseName] = item;
}
}
_logger.LogInformation("Google Drive インデックス読み込み完了: 全{Count}件 (m3u8: {M3U8Count}件, lrc: {LrcCount}件)",
items.Count, m3u8Items.Count, lrcByBaseName.Count);
var newPlaylists = new ConcurrentDictionary<string, PlaylistItem>(StringComparer.OrdinalIgnoreCase);
var newTracks = new ConcurrentDictionary<string, TrackItem>(StringComparer.OrdinalIgnoreCase);
int gradientIndex = 0;
var httpClient = _httpClientFactory.CreateClient();
// 2. Google Drive から各 .m3u8 プレイリストファイルを直接ダウンロードして解析
foreach (var m3u8 in m3u8Items)
{
var playlistName = Path.GetFileNameWithoutExtension(m3u8.local_title);
var playlistId = GenerateStableId("pl_" + playlistName);
var playlist = new PlaylistItem
{
Id = playlistId,
Name = playlistName,
FileName = m3u8.local_title,
CoverGradient = Gradients[gradientIndex % Gradients.Length]
};
gradientIndex++;
try
{
var downloadUrl = $"https://drive.google.com/uc?export=download&id={m3u8.id}";
var m3u8Text = await httpClient.GetStringAsync(downloadUrl);
var lines = m3u8Text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
TrackItem? currentTrack = null;
foreach (var rawLine in lines)
{
var line = rawLine.Trim();
if (string.IsNullOrEmpty(line)) continue;
if (line.StartsWith("#EXTINF:", StringComparison.OrdinalIgnoreCase))
{
currentTrack = ParseExtInf(line, playlistName);
}
else if (!line.StartsWith("#") && currentTrack != null)
{
// ファイル名を取得(例: "Youtube/song.opus" または "song.opus")
var fileName = Path.GetFileName(line.Replace('/', Path.DirectorySeparatorChar));
var baseName = Path.GetFileNameWithoutExtension(fileName);
var relPath = "Youtube/" + fileName;
var trackId = GenerateStableId(relPath);
// Google Drive の該当ファイル情報を引く
if (_itemsByFileName.TryGetValue(fileName, out var opusItem))
{
currentTrack.Id = trackId;
currentTrack.RelativePath = relPath;
currentTrack.FullPath = $"gdrive://{opusItem.id}/{fileName}";
currentTrack.GoogleDriveFileId = opusItem.id;
currentTrack.FileSize = opusItem.file_size;
currentTrack.LastModified = DateTime.UtcNow;
// 同名の LRC 歌詞ファイルが存在するか確認
if (lrcByBaseName.TryGetValue(baseName, out var lrcItem))
{
currentTrack.HasLyrics = true;
currentTrack.LrcFileId = lrcItem.id;
}
playlist.Tracks.Add(currentTrack);
newTracks.TryAdd(trackId, currentTrack);
}
currentTrack = null;
}
}
newPlaylists.TryAdd(playlist.Id, playlist);
_logger.LogInformation("Google Drive プレイリスト読込完了: {Name} ({Count}曲)", playlist.Name, playlist.TrackCount);
}
catch (Exception ex)
{
_logger.LogError(ex, "Google Drive プレイリストダウンロード/解析失敗: {File} (ID: {Id})", m3u8.local_title, m3u8.id);
}
}
// 3. インデックス内の全 .opus ファイルを走査して「すべての曲」プレイリストを構築
var allOpusItems = items.Where(i => i.type == "opus" || i.local_title.EndsWith(".opus", StringComparison.OrdinalIgnoreCase)).ToList();
var allTracksList = new List<TrackItem>();
foreach (var opusItem in allOpusItems)
{
var fileName = opusItem.local_title.Trim();
var baseName = Path.GetFileNameWithoutExtension(fileName);
var relPath = "Youtube/" + fileName;
var trackId = GenerateStableId(relPath);
if (!newTracks.TryGetValue(trackId, out var track))
{
var (artist, title) = ParseArtistAndTitle(baseName);
string? lrcId = null;
bool hasLyrics = false;
if (lrcByBaseName.TryGetValue(baseName, out var lrcItem))
{
hasLyrics = true;
lrcId = lrcItem.id;
}
track = new TrackItem
{
Id = trackId,
Title = title,
Artist = artist,
Album = "YouTube",
DurationSeconds = 0,
RelativePath = relPath,
FullPath = $"gdrive://{opusItem.id}/{fileName}",
GoogleDriveFileId = opusItem.id,
LrcFileId = lrcId,
FileSize = opusItem.file_size,
LastModified = DateTime.UtcNow,
HasLyrics = hasLyrics
};
newTracks.TryAdd(trackId, track);
}
allTracksList.Add(track);
}
// 「すべての曲」プレイリストを先頭に追加
var allPlaylist = new PlaylistItem
{
Id = "all_tracks",
Name = "すべての曲",
FileName = null,
CoverGradient = Gradients[0], // YouTube Red
Tracks = allTracksList.OrderBy(t => t.Title).ToList()
};
newPlaylists.TryAdd(allPlaylist.Id, allPlaylist);
_logger.LogInformation("全曲プレイリスト構築完了: {Count}曲", allPlaylist.TrackCount);
// キャッシュをアトミックに差し替え
_playlists.Clear();
foreach (var kvp in newPlaylists)
{
_playlists.TryAdd(kvp.Key, kvp.Value);
}
_tracksById.Clear();
foreach (var kvp in newTracks)
{
_tracksById.TryAdd(kvp.Key, kvp.Value);
}
_lyricsCache.Clear();
_lastScanTime = DateTime.Now;
LastScanError = null;
_logger.LogInformation("Google Drive ライブラリスキャン完了: プレイリスト {PLCount} 個, トラック合計 {TrackCount} 曲", _playlists.Count, _tracksById.Count);
}
catch (Exception scanEx)
{
LastScanError = $"{scanEx.GetType().FullName}: {scanEx.Message}\n{scanEx.StackTrace}";
_logger.LogError(scanEx, "Google Drive 音楽ライブラリスキャンに失敗しました: FolderId={FolderId}", _googleDriveFolderId);
}
}
finally
{
_scanLock.Release();
}
}
/// <summary>
/// 全プレイリストを取得します
/// </summary>
public IReadOnlyList<PlaylistItem> GetPlaylists()
{
return _playlists.Values.OrderBy(p => p.Id == "all_tracks" ? 0 : 1).ThenBy(p => p.Name).ToList();
}
/// <summary>
/// 指定IDのプレイリストを取得します
/// </summary>
public PlaylistItem? GetPlaylist(string id)
{
_playlists.TryGetValue(id, out var pl);
return pl;
}
/// <summary>
/// 指定IDのトラックを取得します
/// </summary>
public TrackItem? GetTrack(string id)
{
_tracksById.TryGetValue(id, out var track);
return track;
}
/// <summary>
/// 全トラック一覧を取得します
/// </summary>
public IReadOnlyList<TrackItem> GetAllTracks()
{
return _tracksById.Values.OrderBy(t => t.Title).ToList();
}
/// <summary>
/// 指定トラックの歌詞(LRC)を Google Drive から直接取得・パースします
/// </summary>
public async Task<List<LyricLine>?> GetLyricsAsync(string trackId)
{
if (_lyricsCache.TryGetValue(trackId, out var cached))
{
return cached;
}
var track = GetTrack(trackId);
if (track == null || string.IsNullOrEmpty(track.LrcFileId)) return null;
try
{
var httpClient = _httpClientFactory.CreateClient();
var lrcUrl = $"https://drive.google.com/uc?export=download&id={track.LrcFileId}";
var lrcContent = await httpClient.GetStringAsync(lrcUrl);
var lines = lrcContent.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var result = new List<LyricLine>();
var timeRegex = new Regex(@"\[(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?\]", RegexOptions.Compiled);
foreach (var line in lines)
{
var match = timeRegex.Match(line);
if (match.Success)
{
int min = int.Parse(match.Groups[1].Value);
int sec = int.Parse(match.Groups[2].Value);
double ms = 0;
if (match.Groups[3].Success)
{
var msStr = match.Groups[3].Value;
if (msStr.Length == 2) ms = int.Parse(msStr) * 10.0;
else ms = int.Parse(msStr);
}
var totalSeconds = (min * 60) + sec + (ms / 1000.0);
var text = timeRegex.Replace(line, "").Trim();
if (!string.IsNullOrWhiteSpace(text))
{
result.Add(new LyricLine
{
TimeSeconds = totalSeconds,
Text = text
});
}
}
}
var sorted = result.OrderBy(l => l.TimeSeconds).ToList();
_lyricsCache.TryAdd(trackId, sorted);
return sorted;
}
catch (Exception ex)
{
_logger.LogError(ex, "Google Drive 歌詞ダウンロード/パース失敗: TrackId={TrackId}, LrcFileId={LrcId}", trackId, track.LrcFileId);
return null;
}
}
/// <summary>
/// #EXTINF 行を解析して TrackItem を生成します
/// </summary>
private TrackItem ParseExtInf(string extInfLine, string albumName)
{
int duration = 0;
string rawTitle = extInfLine;
var colonIdx = extInfLine.IndexOf(':');
if (colonIdx >= 0)
{
var commaIdx = extInfLine.IndexOf(',', colonIdx);
if (commaIdx >= 0)
{
var durationStr = extInfLine.Substring(colonIdx + 1, commaIdx - colonIdx - 1).Trim();
int.TryParse(durationStr, out duration);
rawTitle = extInfLine.Substring(commaIdx + 1).Trim();
}
else
{
var durationStr = extInfLine.Substring(colonIdx + 1).Trim();
int.TryParse(durationStr, out duration);
}
}
var (artist, title) = ParseArtistAndTitle(rawTitle);
return new TrackItem
{
Title = title,
Artist = artist,
Album = albumName,
DurationSeconds = duration
};
}
/// <summary>
/// タイトル文字列からアーティスト名と曲名を分離します
/// </summary>
private (string artist, string title) ParseArtistAndTitle(string rawTitle)
{
if (string.IsNullOrWhiteSpace(rawTitle))
{
return ("Unknown Artist", "Unknown Title");
}
var hyphenSplit = rawTitle.Split(" - ", 2, StringSplitOptions.RemoveEmptyEntries);
if (hyphenSplit.Length == 2)
{
return (CleanText(hyphenSplit[0]), CleanText(hyphenSplit[1]));
}
if (rawTitle.StartsWith("[") || rawTitle.StartsWith("【"))
{
var endBracketIdx = rawTitle.IndexOfAny(new[] { ']', '】' });
if (endBracketIdx > 0 && endBracketIdx < rawTitle.Length - 1)
{
var tag = rawTitle.Substring(1, endBracketIdx - 1).Trim();
var remaining = rawTitle.Substring(endBracketIdx + 1).Trim();
return (CleanText(tag), CleanText(remaining));
}
}
return ("YouTube", CleanText(rawTitle));
}
private string CleanText(string text)
{
return text.Trim().Trim('"', '\'');
}
/// <summary>
/// 文字列から安定したURLセーフなIDを生成します
/// </summary>
private string GenerateStableId(string input)
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = SHA256.HashData(bytes);
return Convert.ToHexString(hash).Substring(0, 16).ToLowerInvariant();
}
}
+17
View File
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>MusicStreaming</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Update="google_drive_index.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
+173
View File
@@ -0,0 +1,173 @@
using Microsoft.AspNetCore.HttpOverrides;
using MusicStreaming.Class.Models;
using MusicStreaming.Class.Renderers;
using MusicStreaming.Class.Services;
var builder = WebApplication.CreateBuilder(args);
// =========================================================================
// ポート設定: IIS ホスト時は ASPNETCORE_PORT、直接起動時は 8081
// =========================================================================
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT")))
{
builder.WebHost.UseUrls("http://0.0.0.0:8081");
}
// サービス登録
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient();
builder.Services.AddSingleton<MusicLibraryService>();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
options.ForwardLimit = null;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
});
var app = builder.Build();
app.UseForwardedHeaders();
// 初期スキャン(Google Drive 共有フォルダのプレイリスト・楽曲インデックス読み込み)
var libraryService = app.Services.GetRequiredService<MusicLibraryService>();
try
{
await libraryService.InitializeAsync();
}
catch (Exception ex)
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "初期ライブラリスキャン中にエラーが発生しましたが、起動を継続します。");
}
// ルーティング
app.MapGet("/", (MusicLibraryService musicService) =>
{
var playlists = musicService.GetPlaylists();
var allTracks = musicService.GetAllTracks();
return Results.Content(HtmlRenderer.RenderPlayerPage(playlists, allTracks), "text/html; charset=utf-8");
});
app.MapGet("/api/library", (MusicLibraryService musicService) =>
{
return Results.Ok(new
{
playlists = musicService.GetPlaylists(),
allTracks = musicService.GetAllTracks(),
lastScanTime = musicService.LastScanTime,
lastScanError = musicService.LastScanError
});
});
app.MapGet("/api/playlists", (MusicLibraryService musicService) =>
{
return Results.Ok(musicService.GetPlaylists());
});
app.MapGet("/api/playlists/{id}", (string id, MusicLibraryService musicService) =>
{
var pl = musicService.GetPlaylist(id);
if (pl == null) return Results.NotFound(new { error = "Playlist not found" });
return Results.Ok(pl);
});
app.MapGet("/api/tracks", (MusicLibraryService musicService) =>
{
return Results.Ok(musicService.GetAllTracks());
});
// =========================================================================
// Google Drive ダイレクトストリーミング (HTTP 206 Range リクエスト対応)
// =========================================================================
app.MapGet("/api/stream/{trackId}", async (string trackId, MusicLibraryService musicService, HttpContext context, IHttpClientFactory httpClientFactory) =>
{
var track = musicService.GetTrack(trackId);
if (track == null || string.IsNullOrEmpty(track.GoogleDriveFileId))
{
return Results.NotFound(new { error = "Audio track not found" });
}
var client = httpClientFactory.CreateClient();
var downloadUrl = $"https://drive.google.com/uc?export=download&id={track.GoogleDriveFileId}";
var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
// クライアントからの Range ヘッダーを Google Drive に透過転送
if (context.Request.Headers.TryGetValue("Range", out var rangeValues))
{
request.Headers.TryAddWithoutValidation("Range", (string?)rangeValues);
}
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
context.Response.StatusCode = (int)response.StatusCode;
context.Response.ContentType = "audio/ogg; codecs=opus";
// 重要なヘッダーの透過転送
if (response.Content.Headers.ContentLength.HasValue)
{
context.Response.ContentLength = response.Content.Headers.ContentLength.Value;
}
if (response.Content.Headers.TryGetValues("Content-Range", out var contentRange))
{
context.Response.Headers["Content-Range"] = string.Join(",", contentRange);
}
context.Response.Headers["Accept-Ranges"] = "bytes";
// ストリームをパイプ転送
var stream = await response.Content.ReadAsStreamAsync();
await stream.CopyToAsync(context.Response.Body);
return Results.Empty;
});
// =========================================================================
// Google Drive リアルタイム同期歌詞 (.lrc) 取得
// =========================================================================
app.MapGet("/api/lyrics/{trackId}", async (string trackId, MusicLibraryService musicService) =>
{
var lyrics = await musicService.GetLyricsAsync(trackId);
if (lyrics == null)
{
return Results.Ok(Array.Empty<LyricLine>());
}
return Results.Ok(lyrics);
});
// =========================================================================
// ライブラリ再読み込み API
// =========================================================================
app.MapPost("/api/library/reload", async (MusicLibraryService musicService) =>
{
await musicService.ScanLibraryAsync();
return Results.Ok(new
{
message = "Library reloaded successfully from Google Drive",
playlists = musicService.GetPlaylists(),
allTracks = musicService.GetAllTracks()
});
});
// =========================================================================
// 診断・ステータス API
// =========================================================================
app.MapGet("/api/debug", (MusicLibraryService musicService) =>
{
var playlists = musicService.GetPlaylists();
var allTracks = musicService.GetAllTracks();
return Results.Ok(new
{
user = System.Security.Principal.WindowsIdentity.GetCurrent().Name,
processId = Environment.ProcessId,
googleDriveFolderId = musicService.GoogleDriveFolderId,
lastScanTime = musicService.LastScanTime,
lastScanError = musicService.LastScanError,
playlistsCount = playlists.Count,
allTracksCount = allTracks.Count,
storageMode = "Google Drive Direct Cloud Stream (No local physical files)"
});
});
app.Run();
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<DeleteExistingFiles>false</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>false</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>C:\docker\music\</PublishUrl>
<PublishDir>C:\docker\music\</PublishDir>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<SelfContained>false</SelfContained>
</PropertyGroup>
<!-- ① 発行開始前: app_offline.htm を配置して IIS のプロセスを停止し DLL ロックを解除 -->
<Target Name="TakeAppOffline" BeforeTargets="BeforePublish">
<Message Text="[Deploy] app_offline.htm を配置して IIS プロセスを停止します..." Importance="high" />
<WriteLinesToFile File="$(PublishUrl)app_offline.htm"
Lines="&lt;html&gt;&lt;body&gt;Publishing updates...&lt;/body&gt;&lt;/html&gt;"
Overwrite="true" />
<!-- プロセスが完全に終了してファイルロックが解放されるまで 2 秒待機 -->
<Exec Command="powershell -Command Start-Sleep -Seconds 2" />
</Target>
<!-- ② 発行完了後: app_offline.htm を削除して IIS プロセスを自動起動 -->
<Target Name="BringAppOnline" AfterTargets="AfterPublish">
<Message Text="[Deploy] app_offline.htm を削除して IIS アプリケーションを復帰します..." Importance="high" />
<Delete Files="$(PublishUrl)app_offline.htm" />
</Target>
</Project>
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://0.0.0.0:8081"
}
}
},
"MusicLibrary": {
"GoogleDriveFolderId": "19cEGl5nAToDSdlBOkB3vr6-emoF-B86g",
"AutoReloadMinutes": 30
}
}
+1
View File
@@ -0,0 +1 @@
[{"id":"1rXcfmvGq1MZrmyyB35sJb9qXe1koV9vb","local_title":"DECO*27×堀江晶太(kemu) - セカイ feat. 初音ミク.opus","file_size":5280691,"type":"opus"}, {"id":"10ZPe5L5fXX39a0-oIP-tW99ADiErYbGR","local_title":"DECO*27×堀江晶太(kemu) - セカイ feat. 初音ミク.lrc","file_size":3002,"type":"lrc"}, {"id":"1yZYDMc3ICs90z9LBGjTufJeJJaxpX3Zh","local_title":"Giga × Mitchie M - ワーワーワールド feat. 初音ミク&鏡音リン(プロジェクトセカイ テーマ曲).opus","file_size":4434003,"type":"opus"}, {"id":"1UHvmmW_2WHY2mFr5ebPOY5lssh5rhq_6","local_title":"Giga × Mitchie M - ワーワーワールド feat. 初音ミク&鏡音リン(プロジェクトセカイ テーマ曲).lrc","file_size":2584,"type":"lrc"}, {"id":"157SCnU7bNx7TnFfoYn7kJ5JiDrXEjTUN","local_title":"Gunjo Sanka.opus","file_size":5846399,"type":"opus"}, {"id":"1suGxpGg6O5XUTdAXOlCg1KQyKflVODZr","local_title":"Gunjo Sanka.lrc","file_size":2131,"type":"lrc"}, {"id":"1lOsHzHqGETMqkcqn8vbpb57pRJtBE_k7","local_title":"DECO*27 - Journey feat. 初音ミク.opus","file_size":3752575,"type":"opus"}, {"id":"1k69fQHqwltVU8qXI--1yvOvihdHzfxT4","local_title":"DECO*27 - Journey feat. 初音ミク.lrc","file_size":3188,"type":"lrc"}, {"id":"1PYVNiOw_0AQohwYLxS-6Qw9QxEBj4H7m","local_title":"NEO feat. 初音ミク / じん【Official MV】.opus","file_size":4094484,"type":"opus"}, {"id":"1cHvJgg5Kjik32tTyyN4E1soKm9Ho6zT7","local_title":"NEO feat. 初音ミク / じん【Official MV】.lrc","file_size":2579,"type":"lrc"}, {"id":"1F5XDMfpC8g-BZQc1_6gvAVFDrKKlxDct","local_title":"熱風 - kemu feat. 初音ミク.opus","file_size":4100259,"type":"opus"}, {"id":"1IiHkwoKk7-kTVPIrrsQk-IJjZGfo1OgV","local_title":"熱風 - kemu feat. 初音ミク.lrc","file_size":3044,"type":"lrc"}, {"id":"1wWQoaVGxownEOIu1aVa8fplqx3O5K7xt","local_title":"【初音ミク × flower】ペンタトニック【syudou × バルーン】.opus","file_size":4637788,"type":"opus"}, {"id":"1OFqz2MXs8L-OtgJt88J3N29RocBu4u7b","local_title":"DECO*27 - needLe feat. 初音ミク.opus","file_size":5042813,"type":"opus"}, {"id":"142KIdJYoVY7NeHRLBjpj0xvR2vu4beO6","local_title":"DECO*27 - needLe feat. 初音ミク.lrc","file_size":2503,"type":"lrc"}, {"id":"11bvy6KkjleuS4V4XBNkkjfF2SQqKgESY","local_title":"みきとP 『 ロキ 』 MV.opus","file_size":4659919,"type":"opus"}, {"id":"1B3N7AwQsi-zblCGSZKzZ52oh5yNNCW3d","local_title":"みきとP 『 ロキ 』 MV.lrc","file_size":2528,"type":"lrc"}, {"id":"1PM2XDWYEh_3UBzhMN9rA3ctxo93sPt3u","local_title":"テオ / 初音ミク.opus","file_size":4055949,"type":"opus"}, {"id":"1GbTee5x6DoSTHpHM8n9gvBtKS5e-v_-Z","local_title":"テオ / 初音ミク.lrc","file_size":2201,"type":"lrc"}, {"id":"1L7GkO8r2mbPutIJKB_S9R5l4PVod33eC","local_title":"DECO*27 - ヒバナ feat. 初音ミク.opus","file_size":4117851,"type":"opus"}, {"id":"1HA4z8b2RYpuOqVmhs2Y1VdM8LQ6oM2Q1","local_title":"Orangestar - アスノヨゾラ哨戒班 (feat. IA) Official Video.opus","file_size":4236975,"type":"opus"}, {"id":"1NJhdjQ-_Gs2gOz0gN_VSDMlYtLwoPGCi","local_title":"Orangestar - アスノヨゾラ哨戒班 (feat. IA) Official Video.lrc","file_size":1779,"type":"lrc"}, {"id":"1xMrmcY4rFF1iQprWpfS5NhNAdjQ7MJoY","local_title":"青く駆けろ!(Original ver.)/ まらしぃ feat.初音ミク(Hatsune Miku).opus","file_size":4999047,"type":"opus"}, {"id":"1DBjOH7W7Jhzz3RJEx1cBLUC57sSG198t","local_title":"Stella (BLUE BACK Ver.).opus","file_size":6610000,"type":"opus"}, {"id":"1Dp6dC9cO6ydWITXk5KXEd23brwFYkbTd","local_title":"【初音ミク】 ウミユリ海底譚 【オリジナル曲】.opus","file_size":5226781,"type":"opus"}, {"id":"1w6f2ES4ef-i54H2iS7GvSTEjd1BmBZXC","local_title":"【初音ミク】 ウミユリ海底譚 【オリジナル曲】.lrc","file_size":2705,"type":"lrc"}, {"id":"1iQlo_gH6RtehUP9Hg_iGKIYyZMdyX5CU","local_title":"Dramaturgy.opus","file_size":4973108,"type":"opus"}, {"id":"1qOIge9oft6iI8MWuwNbBc-eCaNzaONpm","local_title":"Dramaturgy.lrc","file_size":2909,"type":"lrc"}, {"id":"1YGECXEr-gjUB3cy8AF1F0K085_HJ0hJN","local_title":"Orangestar - 霽れを待つ (feat. 初音ミク) Official Video.opus","file_size":5325674,"type":"opus"}, {"id":"16OYboSXco2yN2Pp7Hx5ZFmSJsCMAg7Tw","local_title":"Orangestar - 霽れを待つ (feat. 初音ミク) Official Video.lrc","file_size":1901,"type":"lrc"}, {"id":"1WeUYBLvowIzl23kwD3fFn9Pr-PsszQWT","local_title":"【初音ミク(1640㍍)】 タイムマシン 【オリジナル】.opus","file_size":5142788,"type":"opus"}, {"id":"1eJ9SHckXIH6hCc55DLVkHkLbY8wCE1sC","local_title":"【初音ミク(1640㍍)】 タイムマシン 【オリジナル】.lrc","file_size":2164,"type":"lrc"}, {"id":"1rooj4lnMkmcS-ugWPUlOxf7eG_d1vRWn","local_title":"初音ミク from Y to Y.opus","file_size":6970735,"type":"opus"}, {"id":"15XCbwRYgmk69H1lwVGlGU-n9jhOehFa7","local_title":"初音ミク from Y to Y.lrc","file_size":4255,"type":"lrc"}, {"id":"1VvgbMyX2Hgs-urSq92Jwt7VX5QDtXGc1","loLine truncated
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0"
dotnet MusicStreaming.dll
pause
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\MusicStreaming.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
+6
View File
@@ -0,0 +1,6 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\auth_info.txt"
"=== MusicStreaming ===" | Out-File $out
& $appcmd list config "MusicStreaming" -section:system.webServer/security/authentication/anonymousAuthentication | Out-File $out -Append
"=== WebImageViewer ===" | Out-File $out -Append
& $appcmd list config "WebImageViewer" -section:system.webServer/security/authentication/anonymousAuthentication | Out-File $out -Append
+8
View File
@@ -0,0 +1,8 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\auth_all.txt"
"=== WebImageViewer Auth ===" | Out-File $out
& $appcmd list config "WebImageViewer" -section:system.webServer/security/authentication/windowsAuthentication | Out-File $out -Append
& $appcmd list config "WebImageViewer" -section:system.webServer/security/authorization | Out-File $out -Append
"=== MusicStreaming Auth ===" | Out-File $out -Append
& $appcmd list config "MusicStreaming" -section:system.webServer/security/windowsAuthentication | Out-File $out -Append
& $appcmd list config "MusicStreaming" -section:system.webServer/security/authorization | Out-File $out -Append
+3
View File
@@ -0,0 +1,3 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\loc_info.txt"
& $appcmd list config "WebImageViewer" | Out-File $out
+7
View File
@@ -0,0 +1,7 @@
$proc = Get-Process -Id 29176 -ErrorAction SilentlyContinue
$out = "C:\docker\music\wp_modules.txt"
if ($proc) {
$proc.Modules | Select-Object ModuleName, FileName | Out-File $out
} else {
"Process 29176 not found" | Out-File $out
}
+8
View File
@@ -0,0 +1,8 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\sec_info.txt"
"=== handlers ===" | Out-File $out
& $appcmd list config "MusicStreaming" -section:system.webServer/handlers | Out-File $out -Append
"=== authorization ===" | Out-File $out -Append
& $appcmd list config "MusicStreaming" -section:system.webServer/security/authorization | Out-File $out -Append
"=== ipSecurity ===" | Out-File $out -Append
& $appcmd list config "MusicStreaming" -section:system.webServer/security/ipSecurity | Out-File $out -Append
+3
View File
@@ -0,0 +1,3 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\web_handlers.txt"
& $appcmd list config "WebImageViewer" -section:system.webServer/handlers | Out-File $out
+4
View File
@@ -0,0 +1,4 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\wp_info.txt"
& $appcmd list wp | Out-File $out
Get-CimInstance Win32_Process -Filter "Name='w3wp.exe'" | Select-Object ProcessId, CommandLine | Out-File $out -Append
+4
View File
@@ -0,0 +1,4 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$out = "C:\docker\music\pool_status.txt"
& $appcmd list apppool | Out-File $out
& $appcmd list site "MusicStreaming" /text:* | Out-File $out -Append
+8
View File
@@ -0,0 +1,8 @@
@echo off
cd /d "%~dp0"
net session >nul 2>&1
if %errorlevel% neq 0 (
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Start-Process cmd.exe -ArgumentList '/c \"\"%~f0\"\"' -Verb RunAs"
exit /b
)
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0debug-iis.ps1"
+26
View File
@@ -0,0 +1,26 @@
# =========================================================================
# IIS 診断スクリプト
# =========================================================================
$logOut = "C:\docker\music\iis_debug_info.txt"
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
"=== MusicStreaming Site Config ===" | Out-File $logOut
& $appcmd list site "MusicStreaming" /text:* | Out-File $logOut -Append
"=== MusicStreaming AppPool Config ===" | Out-File $logOut -Append
& $appcmd list apppool "MusicStreaming" /text:* | Out-File $logOut -Append
"=== WebImageViewer Site Config ===" | Out-File $logOut -Append
& $appcmd list site "WebImageViewer" /text:* | Out-File $logOut -Append
"=== All AppPools ===" | Out-File $logOut -Append
& $appcmd list apppool | Out-File $logOut -Append
"=== Recent IIS Log Entries ===" | Out-File $logOut -Append
Get-ChildItem "C:\inetpub\logs\LogFiles" -Recurse -Filter "*.log" | Sort-Object LastWriteTime -Descending | Select-Object -First 3 | ForEach-Object {
"--- File: $($_.FullName) ---" | Out-File $logOut -Append
Get-Content $_.FullName -Tail 20 | Out-File $logOut -Append
}
Write-Host "Debug info saved to $logOut"
+2
View File
@@ -0,0 +1,2 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
& $appcmd set config "MusicStreaming" -section:system.webServer/security/authentication/anonymousAuthentication /enabled:true /commit:apphost
+6
View File
@@ -0,0 +1,6 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
# サイトの FREB を有効化
& $appcmd set site "MusicStreaming" /traceFailedRequestsLogging.enabled:true
& $appcmd set config "MusicStreaming" -section:system.webServer/tracing/traceFailedRequests /+"[path='*']" /commit:apphost
& $appcmd set config "MusicStreaming" -section:system.webServer/tracing/traceFailedRequests/[path='*']/traceAreas /+"[provider='WWW Server',areas='Authentication,Security,Filter,Compression,Runtime,RequestNotifications,Module,FastCgi,WebSocket',verbosity='Verbose']" /commit:apphost
& $appcmd set config "MusicStreaming" -section:system.webServer/tracing/traceFailedRequests/[path='*']/failureDefinitions /statusCodes:"400-599" /commit:apphost
+3
View File
@@ -0,0 +1,3 @@
$out = "C:\docker\music\all_log_dirs.txt"
Get-ChildItem "C:\inetpub\logs\LogFiles" | Select-Object Name, FullName | Out-File $out
Get-ChildItem "C:\inetpub\logs" -Recurse | Select-Object FullName | Out-File $out -Append
+12
View File
@@ -0,0 +1,12 @@
@echo off
cd /d "%~dp0"
net session >nul 2>&1
if %errorlevel% neq 0 (
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Start-Process cmd.exe -ArgumentList '/k \"\"%~f0\"\"' -Verb RunAs"
exit /b
)
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0fix-iis.ps1"
echo.
pause
+61
View File
@@ -0,0 +1,61 @@
# =========================================================================
# IIS サイト設定スクリプト: UDUKI-PC\サイト\MusicStreaming
# =========================================================================
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Continue"
Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host " IIS サイト [MusicStreaming] の作成・公開を開始します " -ForegroundColor Cyan
Write-Host "=======================================================" -ForegroundColor Cyan
Import-Module WebAdministration -ErrorAction SilentlyContinue
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$siteName = "MusicStreaming"
$port = 8081
$physicalPath = "C:\docker\music"
# 1. 権限設定 (公開ディレクトリのみ)
Write-Host "`n[1/4] フォルダーのアクセス権限を設定中..." -ForegroundColor Yellow
icacls "$physicalPath" /grant "IIS_IUSRS:(OI)(CI)RX" /T | Out-Null
Write-Host "アクセス権限を付与しました。" -ForegroundColor Green
# 2. 既存の不整合なサイト・アプリプールを完全に強制削除
Write-Host "`n[2/4] 既存のサイト・アプリプールを整理中..." -ForegroundColor Yellow
try { & $appcmd stop site "$siteName" 2>$null } catch {}
try { & $appcmd delete site "$siteName" 2>$null } catch {}
try { & $appcmd delete apppool "$siteName" 2>$null } catch {}
try { Remove-Item "IIS:\Sites\$siteName" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
try { Remove-Item "IIS:\AppPools\$siteName" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
Write-Host "整理が完了しました。" -ForegroundColor Green
# 3. アプリケーションプールの作成 (マネージドコードなし)
Write-Host "`n[3/4] アプリケーションプール '$siteName' を作成中..." -ForegroundColor Yellow
$pool = New-Item "IIS:\AppPools\$siteName" -Force
Set-ItemProperty "IIS:\AppPools\$siteName" -Name "managedRuntimeVersion" -Value ""
Set-ItemProperty "IIS:\AppPools\$siteName" -Name "autoStart" -Value $true
Write-Host "アプリケーションプールを作成しました。" -ForegroundColor Green
# 4. サイトの作成とバインディング
Write-Host "`n[4/4] サイト '$siteName' を作成・起動中 (ポート: $port)..." -ForegroundColor Yellow
New-WebSite -Name $siteName -Port $port -PhysicalPath $physicalPath -ApplicationPool $siteName | Out-Null
Start-Sleep -Seconds 1
try {
Start-WebSite -Name $siteName -ErrorAction SilentlyContinue
} catch {}
$finalSite = Get-WebSite -Name $siteName -ErrorAction SilentlyContinue
$state = if ($finalSite) { $finalSite.State } else { "Unknown" }
Write-Host "`n=======================================================" -ForegroundColor Green
Write-Host " [完了] UDUKI-PC\サイト\$siteName の作成が完了しました!" -ForegroundColor Green
Write-Host " ・サイト名: $siteName" -ForegroundColor Green
Write-Host " ・状態: $state" -ForegroundColor Green
Write-Host " ・ポート: $port" -ForegroundColor Green
Write-Host " ・物理パス: $physicalPath" -ForegroundColor Green
Write-Host " ・アプリケーションプール: $siteName" -ForegroundColor Green
Write-Host " ・ローカルURL: http://localhost:$port/" -ForegroundColor Green
Write-Host " ・公開URL: https://mymusic.armonica-vps.work/" -ForegroundColor Green
Write-Host "=======================================================" -ForegroundColor Green
+2
View File
@@ -0,0 +1,2 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
& $appcmd set config "MusicStreaming" -section:system.webServer/handlers /accessPolicy:"Read, Script" /commit:apphost
+2
View File
@@ -0,0 +1,2 @@
$out = "C:\docker\music\app_events.txt"
Get-WinEvent -FilterHashtable @{ LogName = 'Application'; StartTime = (Get-Date).AddMinutes(-5) } | Select-Object -First 15 TimeCreated, ProviderName, Id, Message | Format-List | Out-File $out
+2
View File
@@ -0,0 +1,2 @@
$out = "C:\docker\music\recent_events.txt"
Get-WinEvent -FilterHashtable @{ LogName = 'Application'; StartTime = (Get-Date).AddMinutes(-10) } | Where-Object { $_.ProviderName -match "IIS|AspNetCore|W3SVC" } | Select-Object TimeCreated, Id, LevelDisplayName, Message | Format-List | Out-File $out
+7
View File
@@ -0,0 +1,7 @@
$out = "C:\docker\music\freb_result.txt"
$frebFiles = Get-ChildItem "C:\inetpub\logs\FailedReqLogFiles" -Recurse -Filter "*.xml" | Sort-Object LastWriteTime -Descending
if ($frebFiles) {
Get-Content $frebFiles[0].FullName | Out-File $out
} else {
"No FREB files found in C:\inetpub\logs\FailedReqLogFiles" | Out-File $out
}
+7
View File
@@ -0,0 +1,7 @@
$w3svcLogs = Get-ChildItem "C:\inetpub\logs\LogFiles" -Recurse -Filter "*.log" | Where-Object { $_.FullName -match "W3SVC" } | Sort-Object LastWriteTime -Descending
$out = "C:\docker\music\w3svc_log.txt"
"=== W3SVC Logs ===" | Out-File $out
foreach ($f in $w3svcLogs) {
"--- File: $($f.FullName) (Modified: $($f.LastWriteTime)) ---" | Out-File $out -Append
Get-Content $f.FullName -Tail 30 | Out-File $out -Append
}
+2
View File
@@ -0,0 +1,2 @@
$out = "C:\docker\music\sys_events.txt"
Get-WinEvent -FilterHashtable @{ LogName = 'System'; StartTime = (Get-Date).AddMinutes(-5) } | Where-Object { $_.ProviderName -match "WAS|W3SVC" } | Select-Object TimeCreated, Id, Message | Format-List | Out-File $out
+4
View File
@@ -0,0 +1,4 @@
@echo off
cd /d "%~dp0"
dotnet publish MusicStreaming\MusicStreaming.csproj -c Release /p:PublishProfile=FolderProfile
pause
+21
View File
@@ -0,0 +1,21 @@
# =========================================================================
# MusicStreaming リリースビルド & C:\docker\music\ への自動発行スクリプト
# =========================================================================
Write-Host "MusicStreaming の発行プロセスを開始します..." -ForegroundColor Cyan
$projectPath = "C:\VS2026\MusicStreaming\MusicStreaming\MusicStreaming.csproj"
$publishDir = "C:\docker\music\"
if (-not (Test-Path $publishDir)) {
New-Item -ItemType Directory -Path $publishDir -Force | Out-Null
}
dotnet publish $projectPath -c Release /p:PublishProfile=FolderProfile
if ($LASTEXITCODE -eq 0) {
Write-Host "=========================================" -ForegroundColor Green
Write-Host "正常に発行が完了しました: $publishDir" -ForegroundColor Green
Write-Host "=========================================" -ForegroundColor Green
} else {
Write-Host "発行中にエラーが発生しました。" -ForegroundColor Red
}
+5
View File
@@ -0,0 +1,5 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
# アプリプールを専用の MusicStreaming に戻す
& $appcmd set app "MusicStreaming/" /applicationPool:"MusicStreaming"
& $appcmd recycle apppool "MusicStreaming"
& $appcmd recycle apppool "WebImageViewerPool"
+14
View File
@@ -0,0 +1,14 @@
@echo off
cd /d "%~dp0"
net session >nul 2>&1
if %errorlevel% neq 0 (
echo Elevating to administrator...
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Start-Process cmd.exe -ArgumentList '/k \"\"%~f0\"\"' -Verb RunAs"
exit /b
)
echo Running IIS setup...
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0setup-iis.ps1"
echo.
pause
+61
View File
@@ -0,0 +1,61 @@
# =========================================================================
# IIS サイト設定スクリプト: UDUKI-PC\サイト\MusicStreaming
# =========================================================================
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Continue"
Write-Host "=======================================================" -ForegroundColor Cyan
Write-Host " IIS サイト [MusicStreaming] の作成・公開を開始します " -ForegroundColor Cyan
Write-Host "=======================================================" -ForegroundColor Cyan
Import-Module WebAdministration -ErrorAction SilentlyContinue
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
$siteName = "MusicStreaming"
$port = 8081
$physicalPath = "C:\docker\music"
# 1. 権限設定 (公開ディレクトリのみ)
Write-Host "`n[1/4] フォルダーのアクセス権限を設定中..." -ForegroundColor Yellow
icacls "$physicalPath" /grant "IIS_IUSRS:(OI)(CI)RX" /T | Out-Null
Write-Host "アクセス権限を付与しました。" -ForegroundColor Green
# 2. 既存の不整合なサイト・アプリプールを完全に強制削除
Write-Host "`n[2/4] 既存のサイト・アプリプールを整理中..." -ForegroundColor Yellow
try { & $appcmd stop site "$siteName" 2>$null } catch {}
try { & $appcmd delete site "$siteName" 2>$null } catch {}
try { & $appcmd delete apppool "$siteName" 2>$null } catch {}
try { Remove-Item "IIS:\Sites\$siteName" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
try { Remove-Item "IIS:\AppPools\$siteName" -Recurse -Force -ErrorAction SilentlyContinue } catch {}
Write-Host "整理が完了しました。" -ForegroundColor Green
# 3. アプリケーションプールの作成 (マネージドコードなし)
Write-Host "`n[3/4] アプリケーションプール '$siteName' を作成中..." -ForegroundColor Yellow
$pool = New-Item "IIS:\AppPools\$siteName" -Force
Set-ItemProperty "IIS:\AppPools\$siteName" -Name "managedRuntimeVersion" -Value ""
Set-ItemProperty "IIS:\AppPools\$siteName" -Name "autoStart" -Value $true
Write-Host "アプリケーションプールを作成しました。" -ForegroundColor Green
# 4. サイトの作成とバインディング
Write-Host "`n[4/4] サイト '$siteName' を作成・起動中 (ポート: $port)..." -ForegroundColor Yellow
New-WebSite -Name $siteName -Port $port -PhysicalPath $physicalPath -ApplicationPool $siteName | Out-Null
Start-Sleep -Seconds 1
try {
Start-WebSite -Name $siteName -ErrorAction SilentlyContinue
} catch {}
$finalSite = Get-WebSite -Name $siteName -ErrorAction SilentlyContinue
$state = if ($finalSite) { $finalSite.State } else { "Unknown" }
Write-Host "`n=======================================================" -ForegroundColor Green
Write-Host " [完了] UDUKI-PC\サイト\$siteName の作成が完了しました!" -ForegroundColor Green
Write-Host " ・サイト名: $siteName" -ForegroundColor Green
Write-Host " ・状態: $state" -ForegroundColor Green
Write-Host " ・ポート: $port" -ForegroundColor Green
Write-Host " ・物理パス: $physicalPath" -ForegroundColor Green
Write-Host " ・アプリケーションプール: $siteName" -ForegroundColor Green
Write-Host " ・ローカルURL: http://localhost:$port/" -ForegroundColor Green
Write-Host " ・公開URL: https://mymusic.armonica-vps.work/" -ForegroundColor Green
Write-Host "=======================================================" -ForegroundColor Green
+2
View File
@@ -0,0 +1,2 @@
$appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
& $appcmd set app "MusicStreaming/" /applicationPool:"WebImageViewerPool"
+8
View File
@@ -0,0 +1,8 @@
@echo off
cd /d "%~dp0"
echo =======================================================
echo Google Drive ??????????
echo =======================================================
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0update-index.ps1"
echo.
pause
+39
View File
@@ -0,0 +1,39 @@
# =========================================================================
# Google Drive 最新インデックス更新スクリプト
# (物理ファイルのコピーは一切行わず、メタデータのみ0.1秒で即時更新)
# =========================================================================
Write-Host "Google Drive の最新楽曲情報をスキャン中..." -ForegroundColor Cyan
$dbSrc = "C:\Users\uduki\AppData\Local\Google\DriveFS\102666316863779072237\metadata_sqlite_db"
$tempDb = "C:\VS2026\MusicStreaming\meta_scan.db"
$outJson = "C:\VS2026\MusicStreaming\MusicStreaming\google_drive_index.json"
$publishJson = "C:\docker\music\google_drive_index.json"
if (Test-Path $dbSrc) {
Copy-Item $dbSrc $tempDb -Force
$query = "SELECT id, local_title, file_size, CASE WHEN local_title LIKE '%.opus' THEN 'opus' WHEN local_title LIKE '%.lrc' THEN 'lrc' WHEN local_title LIKE '%.m3u8' THEN 'm3u8' ELSE 'other' END as type FROM items WHERE trashed = 0 AND (local_title LIKE '%.opus' OR local_title LIKE '%.lrc' OR local_title LIKE '%.m3u8');"
$jsonRaw = sqlite3 $tempDb -json "$query"
Remove-Item $tempDb -Force
[System.IO.File]::WriteAllText($outJson, $jsonRaw, [System.Text.Encoding]::UTF8)
if (Test-Path "C:\docker\music") {
[System.IO.File]::WriteAllText($publishJson, $jsonRaw, [System.Text.Encoding]::UTF8)
}
Write-Host "最新のGoogle Drive楽曲インデックスを更新しました!" -ForegroundColor Green
} else {
Write-Host "Google Drive メタデータが見つかりませんでした。" -ForegroundColor Yellow
}
# IIS の MusicStreaming アプリケーションキャッシュを再読み込み
try {
Write-Host "MusicStreaming サービスのキャッシュを再読み込み中..." -ForegroundColor Cyan
$reloadResponse = Invoke-WebRequest -Uri "http://localhost:8081/api/library/reload" -Method Post -UseBasicParsing -TimeoutSec 10
Write-Host "再読み込み完了!最新の楽曲一覧がブラウザに即時反映されました。" -ForegroundColor Green
} catch {
Write-Host "注意: キャッシュ再読み込みエンドポイントの呼び出しに失敗しました。" -ForegroundColor Yellow
}
Write-Host "=========================================" -ForegroundColor Green
Write-Host "処理が完了しました!" -ForegroundColor Green
Write-Host "=========================================" -ForegroundColor Green