public static string updateRating(long id, LinearEnum.RatingValue rating)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("UPDATE PLAYLIST ");
            sb.Append(" SET RATING = ");
            sb.Append((int)rating);
            sb.Append(" WHERE ID = ");
            sb.Append(id);

            return(sb.ToString());
        }
示例#2
0
        private void webServerProc()
        {
            // 管理者権限がない場合は起動しない
            if (!WindowsUtils.IsExecuteAdminRole())
            {
                MessageUtils.showMessage(MessageBoxIcon.Warning, MessageResource.W0005);
                return;
            }

            listener = new HttpListener();
            listener.Prefixes.Add(prefix); // プレフィックスの登録
            try
            {
                listener.Start();
            }
            catch (HttpListenerException httpListenerException)
            {
                // すでにポートが使用中もしくは管理者権限なし
                LinearAudioPlayer.writeErrorMessage(httpListenerException);
                return;
            }

            while (true)
            {
                HttpListenerContext context = null;
                try
                {
                    context = listener.GetContext();
                }
                catch (HttpListenerException)
                {
                    // HTTP通信中に終了されたらどうしようもないので例外を握りつぶす
                }

                HttpListenerRequest  req = context.Request;
                HttpListenerResponse res = context.Response;

                Debug.WriteLine("request url: " + req.RawUrl);

                if (req.RawUrl.IndexOf("/LinearWebService") == -1)
                {
                    // WEBサーバ

                    string reqPath = req.RawUrl;
                    if (reqPath == "/")
                    {
                        reqPath = "ui/" + LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme + ".html";
                    }

                    reqPath = reqPath.Replace("/", "\\");
                    reqPath = Regex.Replace(reqPath, "\\?.*", "");

                    // リクエストされたURLからファイルのパスを求める
                    string path = docRoot + reqPath;

                    // ファイルが存在すればレスポンス・ストリームに書き出す
                    if (File.Exists(path))
                    {
                        byte[] content = File.ReadAllBytes(path);
                        //string s = File.ReadAllText(path, Encoding.UTF8);
                        //byte[] content = Encoding.UTF8.GetBytes(s);
                        res.Headers[HttpResponseHeader.ContentType] = GuessContentType(Path.GetExtension(path));
                        res.OutputStream.Write(content, 0, content.Length);
                    }
                }
                else
                {
                    // RESTサービス
                    // TODO:変なもの受け取ったら落ちる

                    WebServiceResponseInfo response = new WebServiceResponseInfo();
                    var dict = req.QueryString;
                    var reqParamJsonString = JsonConvert.SerializeObject(
                        dict.AllKeys.ToDictionary(k => k, k => dict[k])
                        );

                    Debug.WriteLine("req data: " + reqParamJsonString);
                    WebServiceRequestInfo request =
                        JsonConvert.DeserializeObject <WebServiceRequestInfo>(reqParamJsonString);

                    response.action = request.action;
                    switch (request.action)
                    {
                    case "play":
                        Action playAction = () =>
                        {
                            LinearAudioPlayer.PlayController.play(LinearGlobal.CurrentPlayItemInfo.Id,
                                                                  false, false);
                        };
                        LinearGlobal.MainForm.BeginInvoke(playAction);
                        break;

                    case "pause":
                        Action pauseAction = () =>
                        {
                            LinearAudioPlayer.PlayController.pause();
                        };
                        LinearGlobal.MainForm.BeginInvoke(pauseAction);
                        break;

                    case "stop":
                        Action stopAction = () =>
                        {
                            LinearAudioPlayer.PlayController.stop();
                        };
                        LinearGlobal.MainForm.BeginInvoke(stopAction);
                        break;

                    case "previous":
                        Action previouspAction = () =>
                        {
                            LinearAudioPlayer.PlayController.previousPlay();
                        };
                        LinearGlobal.MainForm.BeginInvoke(previouspAction);
                        break;

                    case "forward":
                        Action forwardAction = () =>
                        {
                            if (LinearAudioPlayer.PlayController.isPlaying())
                            {
                                LinearAudioPlayer.PlayController.endOfStream();
                            }
                        };
                        LinearGlobal.MainForm.BeginInvoke(forwardAction);
                        break;

                    case "voldown":
                        Action volDownAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol -= 5;
                            if (vol < 0)
                            {
                                vol = 0;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var voldownActionResult = LinearGlobal.MainForm.BeginInvoke(volDownAction);
                        voldownActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "volup":
                        Action volUpAction = () =>
                        {
                            int vol = LinearGlobal.Volume;
                            vol += 5;
                            if (vol > 100)
                            {
                                vol = 100;
                            }
                            LinearGlobal.Volume = vol;
                            LinearGlobal.MainForm.ListForm.setVolume();
                        };
                        var volupActionResult = LinearGlobal.MainForm.BeginInvoke(volUpAction);
                        volupActionResult.AsyncWaitHandle.WaitOne();
                        response.volume = LinearGlobal.Volume;
                        break;

                    case "getplayinfo":
                        if (LinearAudioPlayer.PlayController != null)
                        {
                            response.playInfo  = LinearGlobal.CurrentPlayItemInfo;
                            response.isPlaying = LinearAudioPlayer.PlayController.isPlaying();
                            response.isPaused  = LinearAudioPlayer.PlayController.isPaused();
                            response.seekRatio = (int)(((float)LinearAudioPlayer.PlayController.getPosition() /
                                                        (float)LinearAudioPlayer.PlayController.getLength()) * 100);
                            if (response.seekRatio == 100)
                            {
                                response.seekRatio = 0;
                            }
                        }

                        break;

                    case "seek":
                        Action seekAction = () =>
                        {
                            double value = ((double)LinearAudioPlayer.PlayController.getLength()) *
                                           request.seekPosition;
                            LinearAudioPlayer.PlayController.setPosition((uint)value);
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(seekAction);
                        break;

                    case "getthemelist":
                        var themelist = new List <string>();
                        var filePaths = FileUtils.getFilePathList(
                            Application.StartupPath + LinearConst.WEB_DIRECTORY_NAME + "ui", SearchOption.TopDirectoryOnly);
                        foreach (string path in filePaths)
                        {
                            themelist.Add(Path.GetFileNameWithoutExtension(path));
                        }
                        response.themeList    = themelist.ToArray().Reverse().ToArray();
                        response.nowThemeName = LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme;
                        break;

                    case "switchtheme":
                        LinearGlobal.LinearConfig.ViewConfig.WebInterfaceTheme = request.theme;
                        break;

                    case "getnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(10).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "addnowplaying":
                        response.nowPlaying = LinearAudioPlayer.PlayController.getNowPlayingList(request.skip, request.take).Select(gi => new TrackInfo(gi.Id, gi.Title, gi.Artist, gi.Rating)).ToArray();
                        break;

                    case "getanalyzeinfo":
                        var ai        = new AnalyzeInfo();
                        var startDate = SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL056);
                        if (startDate != null)
                        {
                            ai.StartDate         = startDate.ToString().Substring(0, 10);
                            ai.StartDateRelative = DateTimeUtils.getRelativeTimeString(startDate.ToString());
                        }
                        ai.TotalTracksCount         = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL057);
                        ai.TotalFavoriteTracksCount = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL058);
                        ai.TotalPlayCount           = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL059);
                        ai.TotalPalyHistoryCount    = (long)SQLiteManager.Instance.executeQueryOnlyOne(SQLResource.SQL060);
                        response.analyzeOverview    = ai;
                        break;

                    case "getrecentlist":
                        var paramList  = new List <DbParameter>();
                        var recentlist = new List <TrackInfo>();
                        var limit      = request.limit;
                        if (LinearGlobal.CurrentPlayItemInfo != null && request.offset == 0)
                        {
                            var ci = LinearGlobal.CurrentPlayItemInfo;
                            recentlist.Add(new TrackInfo(ci.Id, ci.Title, ci.Artist, "", "", ci.Rating));     // NowPlaying
                            limit--;
                        }
                        paramList.Add(new SQLiteParameter("Limit", limit));
                        paramList.Add(new SQLiteParameter("Offset", request.offset));
                        recentlist.AddRange(SQLiteManager.Instance.executeQueryNormal(SQLResource.SQL061, paramList).Select(o => new TrackInfo((long)o[0], o[1].ToString(), o[2].ToString(), o[3].ToString(), o[4].ToString(), int.Parse(o[5].ToString()))));
                        response.recentListen = recentlist.ToArray();

                        var offset = request.offset - limit < 0 ? 0 : request.offset - limit;
                        response.pagerPrevious = request.offset == 0 ? -1 : offset;
                        response.pagerNext     = response.recentListen.Length < limit ? -1 : request.offset + limit;
                        break;

                    case "gettopartist":
                        var sql       = SQLResource.SQL062;
                        var rangeType = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where = "";
                        if (rangeType != RangeType.ALL)
                        {
                            where =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType]);
                        }
                        else
                        {
                            sql = SQLResource.SQL064;
                        }
                        sql = sql.Replace(":Condition", where);
                        var topArtists = SQLiteManager.Instance.executeQueryNormal(sql, new SQLiteParameter("Limit", request.limit));
                        if (topArtists.Length > 0)
                        {
                            double maxcount = topArtists.Max(o => (long)o[1]);
                            response.topLists =
                                topArtists.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString(), (long)o[1],
                                                  (int)((int.Parse(o[1].ToString()) / maxcount) * 100), o[2].ToString()))
                                .ToArray();
                        }
                        break;

                    case "gettoptrack":
                        var sql2       = SQLResource.SQL063;
                        var rangeType2 = (RangeType)Enum.Parse(typeof(RangeType), request.rangeType);
                        var where2     = "";
                        if (rangeType2 != RangeType.ALL)
                        {
                            where2 =
                                string.Format(
                                    "WHERE PH.PLAYDATETIME >= DATETIME(DATETIME('NOW','LOCALTIME'), '{0}','LOCALTIME')",
                                    _rangeDictionary[rangeType2]);
                        }
                        else
                        {
                            sql2 = SQLResource.SQL065;
                        }
                        sql2 = sql2.Replace(":Condition", where2);
                        var topTracks = SQLiteManager.Instance.executeQueryNormal(sql2, new SQLiteParameter("Limit", request.limit));
                        if (topTracks.Length > 0)
                        {
                            double maxcount2 = topTracks.Max(o => (long)o[2]);
                            response.topLists =
                                topTracks.Select(
                                    o =>
                                    new TrackInfo(o[0].ToString() + " - " + o[1].ToString(), (long)o[2],
                                                  (int)((int.Parse(o[2].ToString()) / maxcount2) * 100), o[3].ToString(),
                                                  int.Parse(o[4].ToString()))).ToArray();
                        }
                        break;

                    case "ratingon":
                    case "ratingoff":
                        if (request.id == -1)
                        {
                            break;
                        }
                        LinearEnum.RatingValue rating = request.action == "ratingon" ? LinearEnum.RatingValue.FAVORITE : LinearEnum.RatingValue.NORMAL;

                        Action setRatingAction = () =>
                        {
                            var rowIndex = LinearAudioPlayer.GridController.Find((int)GridController.EnuGrid.ID, request.id.ToString());
                            if (rowIndex != -1)
                            {
                                LinearAudioPlayer.GridController.setRatingIcon(rowIndex, rating);
                            }
                            if (request.id == LinearGlobal.CurrentPlayItemInfo.Id)
                            {
                                LinearGlobal.MainForm.setRating((int)rating);
                            }
                        };
                        LinearGlobal.MainForm.ListForm.BeginInvoke(setRatingAction);

                        SQLiteManager.Instance.executeNonQuery(
                            SQLBuilder.updateRating(
                                request.id, rating));
                        break;

                    case "skipnowplaying":
                        Action skipNowPlayingAction = () =>
                        {
                            LinearAudioPlayer.PlayController.skipPlayingList(request.id);
                            LinearAudioPlayer.PlayController.play(request.id, false, true);
                        };
                        LinearGlobal.MainForm.BeginInvoke(skipNowPlayingAction);

                        break;

                    case "getartwork":
                        if (LinearGlobal.CurrentPlayItemInfo.Artwork != null)
                        {
                            try
                            {
                                if (request.artworkSize == 0)
                                {
                                    request.artworkSize = 150;
                                }
                                Bitmap thumbnail = new Bitmap(request.artworkSize, request.artworkSize);
                                using (Graphics g = Graphics.FromImage(thumbnail))
                                {
                                    g.InterpolationMode =
                                        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                    g.DrawImage(LinearGlobal.CurrentPlayItemInfo.Artwork, 0, 0, request.artworkSize, request.artworkSize);
                                }
                                var artworkDirectoy = Application.StartupPath +
                                                      Path.Combine(Path.Combine(LinearConst.WEB_DIRECTORY_NAME, "img"), "artwork");
                                Directory.CreateDirectory(artworkDirectoy);
                                var artworkFileName = string.Format("{0}.png",
                                                                    LinearGlobal.CurrentPlayItemInfo.Id);
                                var artworkThumbFileName = string.Format("{0}-thumb.png",
                                                                         LinearGlobal.CurrentPlayItemInfo.Id);
                                LinearGlobal.CurrentPlayItemInfo.Artwork.Save(artworkDirectoy + "\\" + artworkFileName,
                                                                              System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Save(artworkDirectoy + "\\" + artworkThumbFileName,
                                               System.Drawing.Imaging.ImageFormat.Png);
                                thumbnail.Dispose();
                                var oldfiles =
                                    Directory.GetFiles(artworkDirectoy, "*.png")
                                    .Where(a => Path.GetFileName(a).IndexOf(LinearGlobal.CurrentPlayItemInfo.Id.ToString()) == -1);
                                foreach (var file in oldfiles)
                                {
                                    File.Delete(file);
                                }
                                response.artworkUrl      = "../img/artwork/" + artworkFileName;
                                response.artworkThumbUrl = "../img/artwork/" + artworkThumbFileName;
                            }
                            catch (Exception)
                            {
                                response.artworkUrl = "";
                            }
                        }
                        else
                        {
                            response.artworkUrl = "";
                        }
                        break;
                    }


                    string resJsonString = JsonConvert.SerializeObject(response);
                    byte[] responseByte  = Encoding.UTF8.GetBytes(resJsonString);
                    res.OutputStream.Write(responseByte, 0, responseByte.Length);
                }
                res.Close();
            }
        }